How to structure code in an unit test

When you create your unit tests for a method in the SUT (software under test) you will ask yourself how to structure the code in the test method.
I saw two kind of syntaxes which help to structure the code in a unit test method (well, actually there are at least three, but the third syntax is just chaos, so this is definitely not the way how to do it).

SEVT-Syntax

[TestFixture]
public class ThingTest
{
    [Test]
    public void TestSomething()
    {
        // Setup

        // Exercise

        // Verify

        // Teardown
    }
}

I found this syntax in the xUnit Test Patterns book by Gerard Meszaros. Obviously this syntax is inspired by classic unit frameworks (like junit or nunit). There is one thing, which could be critical: this syntax could be misused when in the teardown block exist code, which has to run always (in other words, which has to be correctly in teardown-method). But when an assert fails, the teardown block would not be invoked. To prevent this case, you have to do extra effort (try/finally construct).
Gerard Meszaros named this usage of the syntax Four-Phase Test. He also showed, that the last phase (the teardown block) could be done by a teardown-method.

AAA-Syntax

[TestFixture]
public class ThingTest
{
    [Test]
    public void TestSomething()
    {
        // Arrange

        // Act

        // Assert
    }
} 

This syntax I found on the blog of William Wake and ayende. I prefer this syntax, because it sounds good and therefore I don’t forget it. I like also the words which are more precise and there are no competition with the setup- or teardown-methods. It is also clear where to put the asserts.

Conclusion

The most important thing is that you structure your code in your unit-test. It is also very important that you test only one concern per test method. A syntax helps you to create readable, maintainable and specific (one test-concern per test method) tests.

Share

You may also like...

3 Responses

  1. Jonas says:

    I think the difference between SEVT (did you invent that abbreviation?) and AAA is marginal in the context of unit-tests.

    As I see it, AAA should be looked at in the context of mocking, where it can be contrasted with Record-Replay.

    See also the interesting acrticle by Jay Fields:
    http://blog.jayfields.com/2008/11/ubiquitous-assertion-syntax.html

  2. Patrick says:

    @Jonas
    I didn’t found an suitable abbreviation for the four-phase test syntax, so I named it SEVT.
    I agree with you, that the AAA syntax is used in the mocking context. But the syntax shouldn’t be used only with mocking. It’s a great help to create simple and well structured unit tests.

  1. 30.03.2010

    […] could use the AAA-Syntax (Arrange-Act-Assert). Also more extended features like the ordered calls with the using syntax is […]

Leave a Reply