Yesterday morning I mentored two people for about 3 hours on how to think about and how to do TDD (Test Driven Development). I was a bit nervous beforehand as it was the first time I’ve formally explained and demonstrated TDD.
We started by talking about how TDD gives you a set of test cases that can help you validate the function of your libraries at a low level (now and in the future). Even more, how it encourages you to think through the design of your classes and methods because it forces you the be the first consumer of your code.
We started with what many people would consider a dangerous beginning, but it turned out really well. We began by writing test cases for existing methods and retrofitting the tests.
One method we tested just generated a random string that was then used by a CAPTCHA component. The length of the string was determined by an Integer parameter on the method. Our first step was to write a test that expected an exception if you put in a negative number. We pretty quickly decided that any length <=0 was an error condition, so we did a bit of refactoring to support that change in the method.
Next we verified that if you passed in the numbers 5, 10, 15 etc; that the length of the string actually matched. No problems there.
We were running out of interesting tests pretty quickly when Shirley stated the obvious that Carl and I had overlooked. We needed to validate that the numbers were actually random. So we put in a test that passed in the number 7 four times and sure enough the Random implementation wasn’t being seeded properly.
So in a short time, we were able to significantly improve the design of a preexisting component using TDD. There were three of us coding and discussing it, so it was very interactive and tied to real code they were using. TDD really is primarily a design technique first and a testing technique second.
We found that even though the methods were already implemented, we were able build up a great set of test cases that will keep those methods from being messed up in the future even if their implementation is updated later on. Better yet, we were able to fix the design in some significant cases. Who wants a random string generator with non-random output?
Best of all, when we were done Shirley walked away with a smile and said “this is really cool.”