Does Unit Testing Add Value When We're Not Doing TDD?
Someone asked this question on Quora.
Does unit testing add value when we’re not doing TDD?
Yes, of course.
I “discovered” systematic unit testing while working at IBM in the late 1990s. I grew tired of believing that I’d finished a task only to find myself under a pile of bug reports a few days later. It felt like the finish line always lay out of reach: I’d have moved on to the new task only to have to return to the preceding one three days later—after I’d forgot some of the key context that I needed to do it. I figured that I needed to do a better job of finding silly mistakes myself, so I started to learn about testing.
I wasn’t doing TDD. Almost nobody was doing it worldwide (exaggeration, but it was 1999, so not much of one). Certainly nobody anywhere near me at IBM Toronto was doing it. No problem: since tests use production code but production code never ever ever depends on tests, I could write all the tests I want and simply not include those files in The Build, so that they wouldn’t bother anyone else.
If you want it to work, then you probably need to test it, at least a little.
The question continued.
Is it a good use of developer expense if the unit tests are being implemented post-facto or is it only cost effective to create unit test for the new code going forward?
As for whether to add tests to existing code or only write tests for new code, I recommend programmers to follow three simple rules when they first start any systematic unit testing (or test-first programming or TDD): (1) all new code requires failing tests; (2) add tests to existing code when you need to change it; (3) add tests to existing code when you need to understand it (even if you aren’t going to change it). Otherwise, don’t add tests to existing code.