Writing Better and Readable Tests with The AAA Pattern

Writing Better and Readable Tests with The AAA Pattern

Islam NEGM's photo
Islam NEGM
Β·Jan 24, 2021Β·

4 min read

I wrote this quick readme-style post to refer my colleagues to it when talking about the familiar AAA style in writing the tests. I will discuss what is it and why it is so important to write the tests in this style.

What is AAA?

AAA stands for (Arrange, Act and Assert), it's one of the most used styles in writing the tests in a pretty format. I believe if you searched on the word "unit testing" in Google you will find a lot of tutorials that are using this style.

void test_function(void)
{
  /* Arrange */
  int expected = 10;
  int actual = 0;
  /* Act */
  actual = add(1,9);
  /* Assert */
  assert(actual, expected);
}
  • Arrange: Here you arrange the environment for the API or the probe that you're testing, if there any initialization or any usage of different APIs you can use it here.
  • Act: This is the main act of test, this is why all the arrangement has been done.
  • Assert: The check you're using to test the return of the act, usually it is an assert-related function.

Why AAA is Better Than Writing the Tests Without This Style?

Some people will ask, what is the advantage that I will get if I followed this style? Well let me put this in two replies:

Short Answer

It will make your code more readable for your colleagues and also for users.

Note: Yes, you can use your tests as a way of documenting the usage of your APIs.

Long Answer

  1. Your code readers, aka. reviewers and users , will appreciate if they could expect the structure that you're following to define a test. It will be more appreciated if you're using one of the famous standard, like AAA , formats to write your own.
  2. In case of long and complex tests, which is the norm , code readers can easily spot what you are trying to check in this test and what are the steps that they need to "arrange" before they can "act".
  3. Enhance the decorative flair of your code, as it always will be good if you've the same consistent and simple style when writing your code.

What Do You Think?

I'd like to hear what do you think about this style, and if you're using other styles in your daily-life.

More Readings

Β 
Share this