Unittests are an integral part of building quality software and the sole responsibility of the developer.
Here I explain some of the lessons i’ve learned after the last couple of years.
- Unittests takes times to write
I’m even inclined to say that writing your tests should take at least the time as writing your functionality takes. - Start with the unit tests
Start writing your unittests first, setting up just enough of your classes to get the test compiling, this will force you write your test based on the functionality required not the buggy implementation you’ve just written. - Independent
as the name says, a unit test will test a single unit of code, use integration tests to see how parts are working together. - Small
A unit test should test a small bit of functionality, one class, or even one method. I usually write extra unittests that test entire use-cases, but those work next to the normal ones. - Test negatives as wel as positives
Your first test will probably check whether the functionality works when specifying the correct parameters , but also test whether the right results are returned or the correct exceptions are thrown when specifying the wrong ones. - Use code coverage tools to measure effectiveness
Coverage tools, like for instance Clover will tell you how much of your code is covered, and also which classes are the most risk (high complexy, low coverage) - Be careful when using mock objects
Using mock objects keeps your unittests indepent but it has the danger that you are testing your mock objects instead of your own functionality, write integration tests - Don’t change outputted results into asserts
It can be very tempting to first see what your class outputs when running a test, and then writing asserts to test on those results, but you will just be validating that bug that is still in there.


