Why you should TDD

tdd
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.

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Test and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s