Test fixtures

I know many people swear by the Arrange-Act-Assert (AAA) pattern for writing unit tests, but I have never liked it. I think it creates unnecessary duplication/repetition when the same arrangement is required in several test methods.

I prefer to have the unit under test initialised to the required state before each test method is run. In automated testing, this baseline state has a name: test fixture. Like its real-world counterpart, the fixture holds the unit in place so that it can be tested in different ways without its state and context changing between method executions.

So, instead of using the AAA pattern where the arrangement is done in each method, I have one test class in which the fixture is set up in one place and several methods act on the fixture and assert the outcomes in different ways. I name the class according to the context (for example, NewCustomerTests and ExistingCustomerTests) and the methods according to what they test (for example, NewCustomerTests.PropertiesAreSet and ExistingCustomerTests.CanBeDisabled).

Most test frameworks have a feature to mark a method for automatic execution before each test method call. For example, in JUnit such a method is decorated with the @Before qualifier; in MSTest, the attribute [TestInitialize] identifies such a method.

Organising test code like this helps reduce mindless mechanical tests and repetition, which are two of the main obstacles to TDD adoption.

Leave a Reply