So I’ve started to do a lot more unit tests than I usually do while working on Minim 2.0. I’m not doing test driven development, I made my thoughts on that clear in an earlier post. However, I feel a lot of the issues people have with unit tests and their use are misplaced. So I thought I’d outline where and why I’m writing unit tests. There are a few rules I have about whether a method should or should not have unit tests.
If you are unit testing properties you are insane. If you are unit testing methods with one or two lines you are insane. There is no need to test these methods. You can understand how they work quickly and easily and if you don’t because these few lines are very complicated then you need to break your code up into a few more lines.
Any methods that have complex logic should have multiple unit tests. The reason is that complex logic is not as easy to understand at a glance, even if you wrote it. As such it is much easier to break. There are very mixed opinions about using automated tests to help develop an app, but almost everyone can agree that automated tests are great if they stop you breaking good code.
Depending on the complexity of the method you should have multiple tests. Obviously you can’t test everything but try to cover the most common case and any edge cases you think could cause problems. For example, if your method should do something differently depending on whether a flag is YES or NO then test both the YES and NO cases.
These are possibly the most important methods to test. These are the ones that are accessed by multiple parts of your app so you will likely be changing quite often. The problem is that while you change it for one part of your application, you may forget to test all the other parts of your application that use it so it is good to make sure that these other parts get what they expect from the method.
What is the point in fixing a buggy method if you’re just going to break it again later? Write tests when you fix a bug to make sure it stays working. This method also means your test suite can grow organically.
These 4 rules are what I use to decide whether I should write a test or not. Often I’ll work on a feature and get it working and then go through my methods and decide what would be worthwhile writing tests for. This way I can focus on development and then spend a few hours afterwards concentrating on the testing. The added benefit is that I can think again about how my code works, which may lead me to find issues that a unit tests can’t fix.