12 April 2005

Unit Testing Notes

The continuing story of my attempts at Test Driven Development...

I'm now writing a GUI application, a simple calculator. Windows needs a new calculator.

I've structured the application so that all the logic is in a calculator.dll file, the GUI only handles input and output, just as it should. This means I can have a separate test class to test the logic of my calculator.dll. I've used some modified sample code to add an array of buttons to the calculator form dynamically when it loads. This is in a buttonarray.cs file, which I'm not testing as it is part of the GUI.

After years of writing code first and then (maybe) writing tests a lot later, it is a very difficult habit to work against. This time I forced myself to write a unit test first, test it to see that result was red, and then start writing code to turn it green.

The first few tests felt really odd; it was a bit like trying drive somewhere using only reverse gear. Once I had about 10 tests done, and had run out of short term memory to recall exactly what they were, it started to feel more sensible to add another test as a way of starting on the next bit of the problem.

I deliberately didn't spend any time on restructuring or refactorinng the code, I took the approach that if it passed the test then it was complete.

It is true, each time you run the tests and the result is green, it does begin to give you more confidence that the latest change hasn't broken anything. And, when I did break the code trying to handle a particular condition, I was able to roll back a bit and start again.

This does mean that you really can focus on just the problem at hand, the new tiny bit of functionality you are trying to add, because you don't need to worry about breaking anything. If you break it, you will know. It feels a lot safer changing the code, when your tests are automated. It only takes seconds to run all those tests again.

I can see unit tests have some real benefits, so far I am not sure about some of the other claimed benefits.

No comments: