The Arrange, Act and Assert structure for unit tests

The Triple A (AAA) abbreviation: Arrange. Act and Assert is a way to structure your unit tests into 3 sections:

  • Arrange: Assign variables, setup stubs, mocks and test-doubles. This is the preparation for the unit test.
  • Act: Act on the unit under test, this often involves calling a method on the class you are testing.
  • Assert: Check that the expected results are as they should be.

Below is an example from one of my other blog posts, where I first setup the object that I need to test (unit under test) and its dependencies. I then act on the object by calling a method and at the end I assert that I got the correct result:

[Fact]
public void ShouldBeBlogWhenHourIsTen()
{
    //Arrange
    var dateTimeWrapper = new DateTimeWrapper(new DateTime(2020, 01, 01, 10, 00, 00));
    var decision = new Decision(dateTimeWrapper);
	//Act
    var whatToDo = decision.WhatToDo();
	//Assert
    Assert.Equal("Blog!", whatToDo);
}

In the above I added Arrange, Act and Assert as comments, I have been on teams where this was the norm, however I see this used less these days. But for developers that are just starting to write unit tests it may help to force the structure using the comments, for others it might seem verbose. Tests are not always straight forward Arrange, Act and Assert. Sometimes you need to act a little more after you have asserted a result. Other times act and assert can melt together, an example would be to check for exceptions, where there may not be an explicit assert.

I hope this helped you to understand Arrange, Act and Assert better, please let me know in the comments if it did!