Well I hadn't posted for a long time... It is almost 3 AM in Shanghai and I am still not asleep. What keeps me awake is the question "What are unit tests anyway?" :).
I am an ardent fan of test first programming and doing XP for past 1 1/2 years. I am writing this for people who are new to XP or TDD. These concepts are already there for long time and I am elucidating here to show my understanding.
Well lets take off.. Unit tests are
1) Obviously tests and also source of feedback, safety net, confidence builder, saviour of the project and many other gallant titles to follow. I am not going to concentrate on this because they are already covered a lot.
2) When you are testing a class they provide the client's view of usage of the class or the interaction of the class with other classes (Being mocks). This is more interesting one. It helps us in two different ways.
One is it shows if the class, its members, the parameters glue together properly. In other words by using the class in a unit test we can see if we have structured the class properly. Some of the things like proper naming of classes and methods come out during this.
The other way is it shows the distribution of responsibility in a class. This is a difficult part of object orientation. When we see a method being called on a object we see that the method is fulfilling one of responsibility. It also make us think that whether the object should have that responsibility. Do we need to move that to a new class or to an existing one?
These questions lead to a lot of refactoring and then again unit tests help us to make them safer. The second point leads us to the Test Driven Design. The unit tests are actually shaping the classes and driving their design. Thinking about the responsibility at early stage in unit tests also leads us better responsibility distribution, to Single Responsibility principle and all such good things.
I am big fan of tests and welcome tests whenever possible. But the point of tests driving the design makes the test first a more favourable one for me.
Well there are a lot of good things about unit tests.. But with sleep fast approaching I think I have written about the most important ones.
If you want to join me or contra me please add it to the comments.