I find it interesting that unit testing hasn't become an industry standard, demanded practice. As somebody that resisted writing unit tests until I was pushed (read forced) into it, I can somewhat understand any hesitancy. However now that I have seen the difference writing tests has made to my code, I never want to go back.
The three top reasons I think you should unit test your code are:
1. It helps you write better code.
- Unit testing pushes you into writing componentised, modular software. Code that is easy to test is:
- Made up of small reusable objects/methods that obey the principal of having a single concern
- Uses dependency injection to loosely couple these components
- If it's too hard to test or you have to set up too many dependencies and state to test it, you've often designed it wrong.
2. Maintainability.
- Unit tests add confidence when re-factoring - even months/years later.
- (Good) unit tests document code.
- Small modular code (as above) is much easier to understand and changes are generally contained to one place.
3. To lower the bug count
- Unit tests result in less bugs. They don't decrease the number of issues from poor or misunderstood requirements, but they reduce genuine software-not-doing-what-its-meant-to bugs.
Two common reasons I have heard to not unit test (aside from developers lacking the knowledge of how to unit test, as I mentioned above) are:
1. It takes more time
- Like learning anything new, unit testing can take a lot of time when you're new to it and often you find yourself re-factoring code to make it testable (which is good! see point 1 above).
- It takes less time when you're used to it. Quality, well designed software takes time. Which leads to:
2. This product/feature/application is a throwaway will never be reused so doesn't need to be well designed
- That product/feature/application will DEFINATELY be reused. It will be extended, tweaked and changed within it's lifetime. Not only that but it will probably become business critical and someone will have to maintain it. Why would anybody justify writing poor quality software?
I'm not saying you should have 100% test coverage, nor should you unit test every component. As the old saying goes "everything in moderation". I do think unit testing has it's place on every project, and the principles of good design that unit testing encourages certainly do. What is your opinion on testing code?