DEV Community

Alex Pushkarev
Alex Pushkarev

Posted on

Unit testing is a misunderstood concept

Here and there I come across complaints about "unit tests". Here are some examples:

❌"Unit tests are difficult to write"
✅(Yes, if the code base is in a bad shape and/or wasn't designed with a testability in mind)

❌"Unit tests are brittle"
✅(Yes, usually when you write tests for the sake of reaching some coverage goals)

❌"Unit tests are only testing technical implementation, not business value"
✅(Yes, if it the way you write you code under test)

Image description

I have a feeling that some people are too concerned with "what" and "how", while forgetting "why".

❓Why we write tests?
👉To confirm that the code that we intend to ship to the next stage isn't obviously and/or horribly broken

❓Why we could prefer smaller ("unit") tests?
👉They are faster (sometimes 600 times faster!)
👉They are more focused. They test smaller bits of business logic so if a test fails one usually would have a good idea of what might be wrong
👉While doing TDD we might be uncomfortable to focus on a complex behaviours without checking smaller behaviours first
👉They are working as forcing function. In my experience there's a strong positive correlation between how easy it is to write small tests (i.e. code testability) with the code readability and maintainability.

Does it make more sense now?

Top comments (0)