Unit testing fundamentals – AAA approach

What is and why it is nice to use AAA approach?

One of the unit testing fundamentals has become a clear division between data preparation, its use and later assertion if everything has been finely processed. That approach is called AAA – arrange, act & assert.

Arrange

During first step we setup all unit test data that we want to be repeatable, we prepare unit test flow. We instantiate the System Under Test Object – SUT which will be our main tested domain.

Act

Second step is where we get the result from tested method or where we just invoke it, the Act step is where the main SUT action is performed.

Assert

Simply speaking that’s the last step where we are checking if the result from the Act step is correct. Every unit test framework known to me has its own assertions methods.

Example

Below we have an example of mentioned AAA approach for unit testing. Simple class “TestedClass” that is being tested with its only method “GetModulo”. In Arrange step testedClass is instantiated, then we expect to get a result of GetModulo action invocation and ultimately we compare the result with the expected value.

It might be worth mentioning that for this example a NUnit framework has been used. The example shows how important it is to keep the code clean, each of the steps is separated by a new line with an additional short comment. I’m a person not using comments and I try to keep the code self-explanatory however in this particular case I think the comment is crucial for a clear code separation.

 

using NUnit.Framework;

namespace AAAApproachTests
{
    public class TestedClass
    {
        public int GetModulo(int firstNumber, int secondNumber) => 
            firstNumber % secondNumber;
    }
    
    [TestFixture]
    public class Tests
    {
        [Test]
        public void ShouldReturnModuloOfTwoNumbers()
        {
            //ARRANGE
            const int firstNumber = 8;
            const int secondNumber = 3;
            var sut = new TestedClass();
            
            //ACT
            var result = sut.GetModulo(firstNumber, secondNumber);

            //ASSERT
            Assert.AreEqual(2, result);
        }
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *