Throughout my career, I’ve been fussing at software developers about not doing decent unit testing. Recently I had to focus that fussing on myself.
I like the idea of test-driven development, where an automated unit test is developed in conjunction with the product code. But I don’t do it very often. Sometimes it’s because I don’t know if I’ll ever use the code I’m writing again – it’s just a one-off thing that won’t need to be repeated after the code does its work once. Sometimes it’s because of the difficulty in setting up a unit test, like my code that uses Watir to automate Internet Explorer. Some of my excuses are the same kind of excuses that the developers I’ve been fussing at have used.
I’m not ready to draw any big conclusions about unit testing, either for my test automation or for product development, but I do want to relate a success story. I had been struggling for a couple of days with a Perl program that parses an SCL script (OpenSTA’s scripting language). It would read in the SCL file, piece together all the line continuations so I could search each statement as a single entity, modify some of the statements, then split them back up into shorter lines. It was mostly working, but little glitches kept appearing – extra blank lines would appear, a line would be cut off too short, etc. As soon as I fixed one glitch, another would appear – the parsing process was fairly complex.
Finally it dawned on me that if a developer were to describe this problem to me, I would suggest that he immediately write unit tests. So that’s exactly what I did. I tried Perl’s Test::Unit module in earnest for the first time. It took a while to figure out how to set up the tests – the examples in the documentation are too trivial to show how a real unit test would work. But after a few hours, I was adding tests, and the tests were finding bugs. It only took a handful of rounds of adding a test, fixing a bug, then finding and fixing the bugs that the fix uncovered. The glitches were gone.
So while I struggle to find the right balance to determine what test automation code should have unit tests, I’ve learned that the code that isn’t working is definitely a good candidate for unit testing.
Originally published on the Tejas Software Consulting Newsletter blog.