Unit Testing – AAA Pattern

Unit testing is one of the skills a good developer should have.   With it, we can create good code and we can minimize bugs in our code.

Unit testing with the AAA Pattern

The simplest way to do a unit test is to use the AAA Pattern.  The AAA Pattern refers to “Arrange, Act and Assert”.

Imagine that we have a method that receive two integers and will return the sum of both integers.  Lets call it “MySum”.  The method should look like this:

public void int MySum(int a, int b)
{
    return a + b;
}

Arrange

Arrange is the setup we need to make when to test the actual code in our unit testing.  Usually the arrange step consists in creating the variables for the input data we need to inject to our test code. Also, it consist on instantiate any objects we need to pass to the code under test if we are using dependency injection.

In our example, the arrange part will be creating the variables that will hold the values of the two integer that we are going to pass to the MySum method.

// Arrange

int a = 5;
int b = 7;

Act

Act is the step of our testing that we actually invoke our testing code. Here, we inject the data we prepared in the previous step and we call the actual method. Sometimes working with a method under test means that we will receive a return value from it.  This return value will be need it for our next step.

// Act

int result = MySum(a, b);

Assert

Assert is the step in which we verify the result of our method under test. If the method under test return some value, then we check if the value returned is correct. If the method under test manipulates the values of an input parameter, then we check for any changes occurred to the input variable.

// Assert

Assert.AreEquals(12, result);

When we do unit testing in Visual Studio, we can create a Unit Test Project. Using the Unit Testing Project will give us a lot of tools as our disposal. I recommend you to take a look at it.

Anyway, if we are creating a test method for our unit testing for our MySum method in Visual Studio your code should look like this:

[TestMethod]
public void TestMySum()
{
    // Arrange
    int a = 5;
    int b = 7;

    // Act
    int result = MySum(a, b);

    // Assert
    Assert.AreEquals(12, result);
}

Conclusion

Doing unit testing is not a daunting task. It is easy if we have a structure or a pattern. If we stick to the AAA Pattern, doing unit testing will be easy. For me, unit testing are the more exiting part of coding, because we prove that our concepts and ideas are correct.

About the Author

Rodnney

I am a "multi hat" software developer with more than 18 years in experience. I had worked from government agencies, insurance companies, ticketing system and educational business using a lot of technologies like SQL Server, Oracle, ASP.NET, MVC, HTML, CSS, Javascript, Linq, etc.

Leave a Reply