Code4IT

The place for .NET enthusiasts, Azure lovers, and backend developers

Clean Code Tip: AAA pattern for tests: why is it important?

2022-02-22 2 min read Clean Code Tips
Just a second!
If you are here, it means that you are a software developer. So, you know that storage, networking, and domain management have a cost .

If you want to support this blog, please ensure that you have disabled the adblocker for this site. I configured Google AdSense to show as few ADS as possible - I don't want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

Thank you for your understanding.
- Davide

Even though many developers underestimate this part, tests should be written even more clearly than production code.

This is true because, while production code is meant to be executed by the application, good tests allow you to document the behavior of the production code. So, the first consumers of the tests are the developers themselves.

So, how can we write better tests? A simple trick is following the «Arrange, Act, Assert» pattern.

A working (but bad) example

As long as the tests pass, they are fine.

Take this example:

[Test]
public void TestDateRange_WithFutureDate()
{
    var diff = (new DateTime(2021, 2, 8) - new DateTime(2021, 2, 3)).Days;
    Assert.AreEqual(5, diff);
}

Yes, the test passes, but when you need to read and understand it, everything becomes less clear.

So, it’s better to explicitly separate the sections of the test. In the end, it’s just a matter of readability.

AAA: Arrange, Act, Assert

A better way to organize tests is by following the AAA pattern: Arrange, Act, Assert.

During the Arrange part, you define all the preconditions needed for your tests. You set up the input values, the mocked dependencies, and everything else needed to run the test.

The Act part is where you eventually run the production code. The easiest example is to run a method in the System Under Test.

Finally, the Assert part, where you check that everything worked as expected.

[Test]
public void TestDateRange_WithFutureDate()
{
    // Arrange
    var today = new DateTime(2021, 2, 3);
    var otherDate = new DateTime(2021, 2, 8);

    // Act
    var diff = (otherDate.Date - today.Date).Days;

    // Assert
    Assert.AreEqual(5, diff);
}

You don’t need to specify in every method the three different parts, but personally, I find it more readable.

Think of tests as physics experiments: first, you set up the environment, then you run the test, and finally, you check if the result is the one you were expecting.

This article first appeared on Code4IT

Conclusion

This is a really simple way to improve your tests: keep every part separated from the others. It helps developers understand what is the meaning of each test, and allows for easier updates.

Happy coding

🐧