Here is my response to the following question on Quora:
Is it typical for unit tests to have a longer length than the code they are testing?
Yep. And that’s a bad thing.
There are two things that tend to bloat unit tests.
1. Extensive setup
If you find there is a lot of setup code then the problem is that it is difficult for you to test in isolation. Either you are creating complex mocks & stubs — because of too many dependencies; or you are having to handle external state — reading & writing to files or databases, instantiating other objects, configuring environments, etc.
In which case it’s not really a unit test. Which is ok, those tests may have value, but you should probably put them in a different bucket and run them at different times.
2. Overly complex tests
If there are many steps to perform (that are not strictly setup) to accomplish the goal you need to test, then there may be an abstraction you’re missing. Or your code is tightly coupled.
If there are many validations needed — then you’re probably trying to test more than one thing, and need to think about what the goal of this particular test is. You don’t necessarily need to test that every value in your result is correct, or inspect that every expected method has been called in a single test. It can be multiple targeted tests.
If you find that you are duplicating a lot of steps or that you are wanting to validate a lot of things in your tests, it may be because setup is complex, or execution is slow. Again, you may not be dealing with unit tests.
The main goal of units tests is not that your code is tested. Test coverage metrics are garbage anyway. The goal of writing unit tests should be that your code is testable in small units. And that may mean refactoring and thinking about it in terms of independent components. Which is a good thing.
Having good unit tests enables safer refactoring. But refactoring is often needed to have good unit tests. It’s not a catch-22, it’s an iterative process. You may start with a bloated end-to-end test. But being able to run that confidently allows you to make small internal changes until you can have small, isolated units that are quickly and easily testable.
