Why Bother With Unit Tests?
Of course, they usually add time to the development cycle. They can be hard to create. Quite often, they seem pointless; Why do I need to check if my TwoTimesTwo() method returns 4? Of course it's going to!
Well, the benefits of Unit Tests may not always be obvious. Often they're disconnected from the problems caused by not doing them. For example, a manager is not likely to blame a Production issue on the fact that you didn't do Unit tests.
Most of the time, if you release some code that performs what it needs to, nobody cares about the quality. However, the people who will care, are those who want to maintain your code later, especially if it ends up being:
- You; or
- A violent psychopath who knows where you live
Unit Tests can also help to document code, showing you what it should and shouldn't be doing. They can help you understand it better.
But maintainability still isn't enough for many people.
Personally I don’t think anyone can really understand the benefits of Unit Testing until they've written some, and felt the satisfaction of those green ticks, and the confidence they give you. Your code is now rock solid, nobody is going to break it without knowing about it (including yourself).
With Unit Tested code you can be sure that every component is doing what it should be. Acceptance Criteria is another step and I'm a strong proponent of automated behaviour driven integrated tests too. But Unit Tests can be more granular, covering a vast array of tiny details that can otherwise be easily overlooked and become the source of fiddly bugs later on. Also, when bugs are found, usually this results in messy, band aid fixes which make the code less flexible. TDD makes the code more maintainable to start with. The necessity to write SOLID code is increased by the need to ensure the code is highly modular and interface driven.
In the end, the extra time spent building unit tests is returned several times by spending less time fixing bugs and maintaining messy code.
The best way to see the benefits of Unit Tests is to write some. Start easy by writing one specifically to test a bug fix. You can then be sure that bug will never surface again.
Getting started is hard, don't get me wrong. It's like lifting weights for the first time, it's going to hurt. But push through the pain and you'll start to see the benefits. It will get easier.