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.
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
describejust groups together the code that we’re testing. Then the
itpart 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
itis 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.
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.