Arrange, Act and Assert (AAA) Pattern in Unit Testing

Jagadish Hiremath
2 min readOct 23, 2020

--

The AAA (Arrange-Act-Assert) pattern has become almost a standard across the industry. It suggests that you should divide your test method into three sections: arrange, act, and assert. Each one of them only responsible for the part in which they are named after.

So the arrange section you only have code required to set up that specific test. Here objects would be created, mocks setup (if you are using one) and potential expectations would be set. Then there is the Act, which should be the invocation of the method being tested. And on Assert you would simply check whether the expectations were met. More info can be found HERE.

Following this pattern does make the code quite well structured and easy to understand. In general lines, it would look like this:

// arrange
var component = ComponentFixture<UserUploadComponent>;
var user = new User(component);
// act
user.Save();
// assert
mock.Received.SomeMethod();

Please notice the comments that precede each section. Have you ever thought whether you really need them on every single test?

Well, the answer may depend on the developer’s OCD levels. I guess if you think that clean code should be self-explanatory, as you were reading an English text (or whatever other languages for that matter), then it would look quite silly to preempt every section of your text with what is coming next. If that does not sound like a good idea, why should we do that on our code?

Your test code should respect most, if not all, rules of production code. It should avoid meaningless magic numbers, should avoid violating principles like DRY, YAGNI, SRP, and KISS.

While learning a new technique, it can be useful for tricks to reinforce it. Like when learning a foreign language, a teacher would provide templates or pre-populated structures that you just need to fill-in the gaps. The same is here, when you starting with your first tests it does make sense to make those comments so you are doing it right.

Once the student has mastered the technique, and that skill becomes second nature, the template should no longer be necessary.

Conclusion

Test code, in the same way as production code, is supposed to be clean and self-explanatory. Preempting what you are going to do just adds unnecessary clutter. You can still have a clear distinction between the three steps by using spaces and indentation. Which are ultimately the key features the compiler provides you to structure your code.

It does look silly having a comment preceding each paragraph in this text, it tires the reader, as it has to constantly go through the obvious (or skip it). So why would you do that with your code?

--

--

No responses yet