My experiences with TDD have been limited and experimental at best. The point of TDD is to develop your test cases before you do the actual code design and implementation. Sounds funcky right? How can you write the code for test, if you don't have the classes and objects to compile it?
Well, this is how you do it:
- you come up with the object model for the feature you are going to test,
- write up the test case based on the requirements; it will fail initially so don't panic. It's all part of the Grand P-l-a-n,
- write the simplest means to pass the test, like return 1+1; //passes test that asserts for 2
- write the simplest code logic to solve the problem and make the test pass.
TDD is one of the main principles for Agile's Extreme Programming (XP). My encounters with it, as I said, have been limited and experimental at best. The first time I came across actual use of it was at Microsoft's Imagine Cup competition. The code that was to be designed and submitted already had test cases written against it to make sure that what we code matches what they want. That's how you get the points.
The next actual application of it was with a test project that I created at my work recently. I was to design and code this Engine that takes in certain inputs and is supposed to return certain output. A normal regular function. I decided to take the data-driven test approach, kinda like Microsoft's VS Test framework, using Unit Test and Xml.
I put all my expected output and all different permutations of the input criteria as test cases in the Xml file (each Test case was an element in the xml with the expected and input criteria as attributes to the element).
My unit test function was then pretty simple, load the xml to a typed data set, read each row of test case from the data set and apply the input criteria to the engine function, and assert them against the expected output from the Xml.
Of course, I had to write a couple of other test cases to check for corner cases like null inputs, stress conditions etc. But my data was abstracted from my test logic and now I don't have to touch my code in order to add new test cases. Pretty slick huh?
Added bonus: I can use code to generate the xml file as well :)