In a recent code review I noticed a bug that was undetected by the unit tests. Read: all tests passed, but the code was wrong. When asked the developer confessed the unit tests were created after the code was created. That is why you should do Test Driven Development.
The first step in TDD is add a failing unit test. This ensures your test code is correct. Then create code to make the unit test pass. At the end do refactoring, but make sure the tests keep passing. Eat – sleep – rave – repeat.
Can you spot the fault in the nservicebus code below? This is a simplified version of the code I found in the review.
// unit test [Fact] public void FooHandler_sends_BarMessage_when_FooMessage_is_handled() { var msg = new FooMessage(); Test.Saga<FooPolicy>() .When(x => x.Handle(msg)) .ExpectSend<BarMessage>(); } // saga implementation public void Handle(FooMessage message) { // send the wrong message type Bus.Send<FooMessage>(msg => { }); }
Try the code and see the unit test pass. What is going on? Seems like the ExpectSend is not executed. When TDD was used the unit test would pass even without the implementation and the wrong test code wouldn’t go unnoticed.
Move the ExpectSend before the When and the test will fail until you send a BarMessage from the saga implementation. Now you know why to write your tests before you start to implement.