Wednesday, February 03, 2010

Method Scenario ExpectedBehaviour

What do you call your unit test methods? How do you logically structure them? I've been over this before, so it's time for a little refinement. One unit test assembly for every assembly under test. One test fixture for every class under test. Many test methods for every method under test. And to make everything easy to read, every test method should follow this pattern (not my idea, but I wish it was):

Method_Scenario_ExpectedBehaviour

For example if we're testing a new Security class with an Authenticate method, we might create the following test methods inside the SecurityTestFixture class:

Authenticate_UserNotFound_ThrowsAuthenticationException
Authenticate_IncorrectPassword_ThrowsAuthenticationException


Of course no application development should be driven by negative tests - at first you'll want to test that your authentication process works, then later down the line you'll want to make sure that it's robust. So there would likely be more test methods like:

Authenticate_Success_ReturnsPrincipal

Note how easy it is for someone to read the test method name and understand what it was doing. That's on purpose. Also note how the scenarios aren't long and complex, and only one logical unit of work is tested per test method. That's on purpose too. It means it's easy to pinpoint the root cause of failure.

No comments: