Why unit tests coverage should be 100%
Writing unit tests is a commitment that a lot of companies and programmers do not make. This is a mistake. Writing unit tests, as well as all automated tests, is an important part of anyone’s software development job.
I have been maintaining a 100% code coverage on all work I do for over 2 years now and I can not go back to anything less. It is ingrained in my own software development methodology. How and why did I start to do this?
I must admit it was partly because of my competitive nature. At the time we were sitting at around 60% code coverage on a few particular files and maybe 70% overall for the project and a work colleague told me that the rest was “not testable”. I took that as a challenge. It was a fun challenge to do something that I was not sure I could do. Most of the hard to test areas were anonymous functions. The files that were not being covered had quite a few of them. I managed to solve it and got those files to 100% coverage. It was a great sense of accomplishment. After that I decided, why not get it all to 100%? So that is what I worked on during every story. Add a little more here and there or sometimes large percentages.
All this became a game to me. How much could I increase the percent this time? Can I even test this? It became… fun.
I did get the codebase to 100%. It is staying that way. In fact, if it is not 100%, we have a linting rule (it is a Javascript project by the way) that will fail the Jenkins build if that percentage is not met so now my colleagues get to enjoy the fun as well (I say with an evil grin).
So was it worth it? I would say yes. Not only is it a great learning experience for all, because you are forced to write tests that you thought were not possible or are too lazy to write. Additionally, we have also not had any major incidents.
I also recommend adding the desired coverage as a requirement to your build as a rule. There have been a couple of times where I have thought I covered everything but I didn’t and the pull request build failed it.
Do note that I do not advocate just writing tests for coverage. Think about scenarios and write them based on function input or use cases. In other words, you may be at 100% coverage, but you still may be missing tests because valid use cases are missing.
Happy test writing.