One of the tenets of test driven development I used to (ok, I still do sometimes) blow off is that you always start with a failing test. You know the drill – ”red bar, green bar, refactor.”
- Write the test for the new little piece of code
- Run the test and verify that it fails for the right reason
- Implement the code and make the test pass
- Wash, rinse, and repeat
The second part of step 2 in that list is pretty important too and it’s easy to skip it. An obvious, unspoken requirement of doing TDD is that your unit test code needs to be correct. It’s not enough to get the red bar (that’s easy). Make sure the unit test is failing correctly before you start writing the real code. That little sanity check of running the test to see the failure is a good way to quickly validate your unit test.
For example, I routinely employ NMock to create dynamic mock objects in unit tests. In your unit tests you’re telling NMock which methods should be called in the test by passing in strings and setting up the argument expectations. When you’re using NMock won’t get any fancy statement completion or handy compiler errors when you fat finger the name of the methods (NMock2 or Rhino Mocks should alleviate this problem. More on that someday). If you just run the unit test first, you can usually spot any kind of problems with the NMock expectations pretty quickly before that gets confused with the real code. One of my favorite TDD idioms now in .Net is to write the test for a new method, then use ReSharper to generate the method stub to match the signature in the unit test. Out of the box, ReSharper will generate the method with a single line of code “throw new NotImplementedException().” When you run the failing test, you just look to see that you’re breaking because of the NotImplementedException. As soon as I see test output like the example below, I know my test setup is functioning and I can go ahead and implement the new method.
public void CloseViewWhenViewIsDirtyAndUserRespondsOk()
// Define the expected interaction
// Perform the unit of work
// Verify the interaction
—— Test started: Assembly: SampleCode.dll ——
TestCase ‘SampleCode.HumbleDialogBox.PresenterTester.CloseViewWhenViewIsDirtyAndUserRespondsOk’ failed: System.NotImplementedException : The method or operation is not implemented.
c:\documents and settings\jeremy.miller\my documents\visual studio projects\samplecode\humbledialogbox2\presenter.cs(46,0): at SampleCode.HumbleDialogBox.Presenter.Close()
c:\documents and settings\jeremy.miller\my documents\visual studio projects\samplecode\humbledialogbox2\presenter.cs(109,0): at SampleCode.HumbleDialogBox.PresenterTester.CloseViewWhenViewIsDirtyAndUserRespondsOk()
0 succeeded, 1 failed, 0 skipped, took 0.03 seconds.
———————- Done ———————-