The Arrange, Act and Assert pattern

Besides writing unit tests, it is also important to be able to maintain them. To improve the maintainability of a unit test, it is important that you can easily see what it is trying to test and how it does this to accomplish this task. To improve the readibility of your unit test, you can use the most widely accepted pattern within unit testing: Arrange, Act and Assert (AAA) pattern.

The pattern

The pattern is like a rocket launcher, that is devided into 3 parts: preparing everything before you actually start the test, executing the test and finaly verifying the result.

Step 1: Arrange

In the arrange part, you set the stage for your test. Everyting is set up in order to do the actual testing. For example, if you need to stub a proxy that is injected in the constructor of the class you’re testing, this is the right place to go.

Step 2: Act

In the second step, you will perform the actual test. So you call this method, with these test values.

Step 3: Assert

You will check what you wanted to be verified. Is the value that is being returned from your test method the value you were expecting? If not the test failed.

Example

The following code shows a short example of how this could look like.

var myTestMethod = new TestMethod();
var value = myTestMethod.CalculatePercentage();
Assert.IsLessOrEqual(value, 100); 

In the first line var myTestMethod = new TestMethod() we create a new instance of the class we want to test. This is our Arrange part.

In the second line var value = myTestMethod.CalculatePercentage(); we perform the actuall test: the act part.

In the last line we check if the value is equal to the one that was expected, the assert part.

Naming a unit test

Besides this structure, I find it also important that unit tests have a logic name. In this way you can also easily see what it’s doing without having to look into the code itself. Derived from this Arrange, Act, Assert pattern is the following way of given a name to your unit tests:

[MethodUnderTest]_[Scenario]_[ExpectedResult]

So MethodUnderTest describes the name of the method you’re about to test.

With Scenario you give a short description of the scenario you’re about to test.

ExpectedResult describes the result you expect.

In our previous example, we could name our unit test for example: CalculatePercentage_StartPercentage_IsLessThen100.

Posted in Unit testing by Bruno at May 1st, 2021.

Leave a Reply