The three A’s of Unit Testing
Jay Cruz
Posted on July 31, 2021
Testing is an essential part of building Software. When it comes to production-ready applications we need to have reliable and well-tested code with as few bugs as possible. There are many methods available for testing your code. In this article, I’ll go over one of the most popular methods, Unit-testing. Unit-testing involves the testing of specific modules or pieces of code within your app. When writing tests you probably want to follow some sort of pattern to write well structured, readable tests. This is where the AAA pattern comes in. The AAA stands for Arrange, Act, and Assert. This is a great way to make sure we’re covering all aspects of testing a module of code.
Arrange the state of the data to set it up for testing.
Act on the data through some method that performs an action.
Assert that the result from acting on that data is what we expect it to be.
This is the basic flow for using the AAA pattern with any testing framework. To break each of these down using a code example we’ll be using Javascript's Jasmine testing framework. If you’ve not heard of Jasmine before, it’s similar to other testing frameworks you might be familiar with such as RSpec and JSpec. Now let’s write some tests!
Implementing the AAA pattern
For our example, we’ll be testing a User model in Javascript. Our User class constructor will receive a full name object to set its first name, middle initial, and last name properties.
Our User class contains a method getFullName()
that should return the user’s full name. So how do we check that this method does what it says it does? We can write a unit test to make sure we’re getting the correct values. the following code does just that!
So the first part of our test suite is the
describe
method. The describe
just groups together the code that we’re testing. Then the it
part of our test is saying what this specific piece of code should actually do. In this case, it should return the full name. Inside of the body of the it
is where we implement the arrange, act, and assert, giving each part a specific responsibility. The arrange is creating a new instance of User class while act performs the action with the getFullName()
method we’re testing. Assert then assures us if the evaluated result from invoking getFullName()
on our user is exactly what we need it to be.
Conclusion
The AAA pattern gives us simple but effective steps for testing our code. Each step to this pattern has its own job to do. The arrange step sets up our data while the act step performs the actions needed to test it, and the assert will determine if the result from acting on that data is what we expected it to be.
Posted on July 31, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.