They can be seen as a pain point. Unit tests should be fairly simple to implement, but often aren’t as the code under test just isn’t written to be testable.
I’ve spent years trying to add unit tests to legacy code, and it was painful to the point of giving up every time. I did what I could but it always came down to having to refactor so much code to make it testable that I would run out of time and patience.
I’m currently working on code that is new and has hundreds of validations methods. There is no way I could expect anyone to test all of this using any kind of manual testing, it would take weeks, if not months of effort. The solution was blindingly obvious, add unit tests.
I’ve still got some way to go, it takes time to write tests, and a little thought to ensure they are useful. If you’re going to write tests make sure you are testing something that is worth testing.
The stance I’ve taken is to write half a dozen to a dozen tests then run them and check the output. It’s working for me very well and I’m happy with the 70 or so tests I’ve been able to write so far.
Two interesting things have come out of writing these tests so far:
- Some of the validation routines were doing too much, i.e. they were testing 2 or more things rather than just 1. I’ve refactored these as I go and was able to use my tests to validate I haven’t messed anything up.
- I found 2 bugs! It would have taken months for these bugs to have been uncovered and by then I would have been so far away from the code it would have taken me some time to track down and fix. As it was it took me no more than a couple of minutes to fix each.
My code coverage is still pretty low, currently sub 10%, however I’d expect to expand on this over the coming days.
If you’re not writing unit test then make a start. Start with 1 test and add to it over time. Build up your test coverage as and when you can. Target a reasonable test coverage, perhaps start with 10%, then 25% then maybe 75%. Don’t target 100% as this is as close to impossible as to not make sense.
If you work as part of a team then talk to them and encourage them to write tests, figure out how to make code testable, how to write testable code and how to write tests. Don’t forget unit tests are code, so you need to ensure you have coding guidelines in place – you may find that your current code guidelines don’t quite work with tests, just amend to fit, have code guidelines and test code guidelines if you need to.
Whatever you do, make sure you are always making concious decisions and review those decisions as and when required.
That’s about it for now. Thanks for reading and see you next time.