Rob Cook


Home | Donate

Unit testing


2023-06-30

Unit testing is not about about 100% code coverage. Instead the goal is to have a high confidence that your code is doing what you think it is doing. High code coverage is a by-product of that aim. If you focus on the metric, people can game it.

Unit tests should be a part of any modern piece of sustainable development. Static or dynamic languages alike. The argument as to weather they come before the code (test driven development) or after, isn't as important as people make out. Test driven development is a good exploratory tool. In cases where you don't know what you need to code, it is a useful tool for getting you unstuck. I've met few developers who can do this religiously though.

To my mind, tests after the fact are fine. If you have made poor design choices in your code, trying to write unit tests will show them up. Code that is hard to test, is usually also hard to maintain. You will end up refactoring your code whether you test before or after it is written.

Common wisdom also holds that each unit test should test one thing. Some people interpret this to mean one assertion statement in the test. I believe this is wrong. You can have multiple assertions in a single test, as long as they go toward proving the one thing being tested.

Of all the development practices that can improve you as a developer, unit testing is the most impactful. It forces you to think about the structure of your code, the coupling, and the size of each method. It affects code design at a number of levels. Grow to love writing unit tests, but don't get hung up on the arguments and metrics therein.

end