This post is the first in a series on the why, what and how of unit testing. It was originally going to be a single post but there was so much I wanted to cover it didn’t seem right to do it as a single post.
For this post we’re going to look at why you should write unit tests and it’s not an easy place to start, if you were to look online for you’d see a number of varied opinions on the topic. Here’s a couple of arguments for and against unit tests that I’ve come across;
Against unit testing
- Cost time and effort to maintain.
- Unit tests don’t test how a system fits together, you also need integration tests. For example unit testing, concurrent modifications in a multithreaded application is difficult.
- Some code doesn’t lend itself well to testing, consider a function which only calls a series of other functions.
- Some people write unnecessary tests which only exist to increase coverage. (More on this in the next post.)
- Some people change the design to make code testable, this can dilute the architecture
For unit testing
- Unit tests provide a good source of documentation for code, they can tell you how something is used or how it was intended to be used.
- Magic fear removing button. Imagine a button that, when pressed, quickly tells you if your code works. Would you ever be afraid to make changes again? This is what unit testing could do for you!
- Quick feedback. For developers quickly seeing the impact of our code changes is very important, we love feedback!
- For new development unit tests may provide the only means to test the code, particularly if an API or UI isn’t available yet!
While these are all valid points, I can’t help but feel some of the arguments against testing would be less relevant if the tests were better written. Unit tests should be;
- Able to validate their target’s outputs.
- Loosely coupled to the code.
- Not written for the sake of adding coverage.
So as long as you write unit tests that take each of these points into consideration what you’re really getting is a means to document your code, improve your confidence when making changes and provide instant feedback on those changes. Just remember that unit tests can’t be your only form of testing!
Hopefully this has helped explain why it’s good to write unit tests, in the next post we will look at what you should look for when writing your unit tests.