Tuesday, November 7, 2017

Why you should always write unit tests. Event if it is not possible.

I became fan of test driven development couple of years ago, after my colleague Viktor introduced it to our team. I was bit skeptical but soon I realized that I can test my services without the need to deploy the application and laborious data typing into web forms. Over the years I used unit tests and test driven development whenever I had the chance. And I learned a lot about them.
   One thing I learned is that the argument that it is not possible to write unit tests is often just an excuse. The aversion to unit tests is not due to laziness but due to people not knowing the true benefits of unit tests.
   Here are two most recurring myths:

Unit tests test only happy day scenario. That's basically true, although it depends on the developer, who might include some border condition or invalid cases. But it is most useful when you are refactoring or changing some functionality, which is on any live project almost always. On any big project even subtle changes can break some remote functionality.

It takes time and effort to write and maintain unit tests. Yes, it takes effort. But deploying application and typing data takes even more effort. Simulating even most common possibilities takes even more time. I've never felt that writing unit tests delays me. Some scientific papers have shown that development with unit tests requires equal time as doing without it, but the resulting code was less bugy.

But the greatest benefit is the code readability. It requires "special" skills to test driven develop large unreadable method with spaghetti code. Instead you usually end up with many small methods that do little bit. Such code is much more readable and maintainable. If you ever end-up with such large and spaghetti method, with unit test it is very easy to refactor the code. The unit tests also serve as a kind of documentation. It is much easier to read unit tests and see method inputs and outputs, instead of guessing or reading method code.