Thursday, May 13, 2010

Write a failing test first

Checking a functionality of a Struts2 interceptor I realized that we forgot to check a condition. Adding the correction was trivial, but I resisted. I first added a failing test, even though the class had no tests at all (this was justified by the fact that most methods are actually pretty simple one-liners).

Yet, an error lurched its way from behind.

The answer is NOT the code fix. At least, not only the code fix. Because other errors are lurking, and I don't want to be in the balance: I want to avoid regression(s). There are no excuses, as testing with Struts2 is much easier than it was with Struts.

That said, I wrote two test cases to avoid regressions on what I knew was working. Green. Then I added another test case that checked the failing condition. Red, as supposed. Only at this point I could add the magical line of code I needed. Back to green. Now we're going somewhere. And I left my camp (slightly) better than how I found it.

Then it was time for some riskless refactoring (well maybe not riskless, but close). Following Steve Freeman suggestions, I changed the names of a couple of methods to make them more expressive. Of course I could have done this before, but having a test harness makes you feel less... vulnerable. Once you get the habit, it is hard to get rid of it. And I don't want to get rid of it :-) on the contrary, I want to keep the ball rolling.

No comments: