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)

19 Valuable Github Repositories for Beginners

19 Valuable GitHub Repositories for beginner devs looking to take the first step into the web development career.