D E V M A T E

Loading

Illustration - man sitting in front of laptop, big screens with code in the background
Patterns enable code quality also for unit tests. Using the same structure in all of your tests saves most of your time in unit testing on the long run, by helping you and others easily understand the content of test cases, as well as maintaining them over time. I elaborate on this fact in more details in my free ebook series “The 9 Fundamental Rules for Better Code Every Day.” (subscribe here), as I’ve already discussed in another article.
 
The most famous pattern is Arrange-Act-Assert. Its simplicity allows it to be applied to any kind of Unit Test, enabling Unit Tests to be more readable, structured, and maintainable.
In its essence, this pattern consists of the following three parts (you guessed right): Arrange, Act, Assert.
  • Arrange: First, everything is prepared for the test case to be carried out. Hier wird das System und die Code-Unit vorbereitet, die Eingabedaten und erwarteten Ergebnisse definiert und ggf. die Mocks erstellt um den Testfall frei von Abhängigkeiten zu machen.
  • Act: In this part, the action happens. The code unit to be tested is executed using the previously prepared data, and the results of this execution (the actual result of the execution) are collected.
  • Assert: Finally, the actual result obtained in the “Act”-part is compared with the expected results (prepared in the “Arrange”-part). In this final part, it is verified whether the tested code unit works as expected.
In the following, this pattern is demonstrated using some examples written with C# and NUnit.
 
AAA test pattern explained - Example Code Picture 1
 
AAA test pattern explained - Example Code Picture 2
 
AAA test pattern explained - Example Code Picture 3
 

AAA test pattern explained - Example Code Picture 4

AAA test pattern explained - Example Code Picture 5

AAA test pattern explained - Example Code Picture 6

You can download the code examples as a .cs-file here: aaa_examples.
 
What do you think of these examples?
Do you know some good examples that you want to add?
What is your experience with the AAA-pattern?
Let me know in the comments section below.
 
written by Daniel Lehner

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Want to experience the magic of devmate?
Join A Live Product Demo
Get Free Access Now to
9 eBooks!
All about Automated Software Testing
Proven experts
Learn to save up to 75% of your test efforts
Get Free Access Now!
Get Access Now! & Save 50%
Personal Trainer FREE Nutrition Custom Workout App
Get Access Now!
eBook Download
Enter your details to get your free ebook!
All about Automated Software Testing
Download Free Ebook
SUBSCRIBE
MY WEB
NEWSLETTERS
Lorem ipsum dolor sit amet, consectetur adipiscing