Dependency Injection and Testing in JUnit 5. Part 2

It's time for the second article in our series about Dependency Injection and Testing in JUnit 5. This time we look at repeated tests.

2. Repeated tests

JUnit 5 provides the ability to repeat a test a specified number of times by annotating a method with @RepeatedTest and specifying the total number of repetitions desired. This may be particularly useful when some conditions may change from one execution of a test to another one. Each invocation of a repeated test behaves like the execution of a regular @Test method with full support for the lifecycle callbacks and extensions.

In addition to specifying the number of repetitions, a custom display name can be configured for each repetition via the name attribute of the @RepeatedTest annotation. The following placeholders are currently supported:
  • – {displayName}: display name of the @RepeatedTest method
  • – {currentRepetition}: current repetition number
  • – {totalRepetitions}: total number of repetitions

Listing 3 shows the usage of repeated tests, of the display name placeholders and of the RepetitionInfo parameters. The scenario of the first repeated test verifies that the execution of the add method from the Calculator class is stable and it always provides the same result. The scenario of the second repeated test verifies that collections follow the appropriate behavior: a list is receiving a new element at each iteration, but a set will not get duplicate elements, even if we try to insert it a few times.

The usage of repeated tests Dependency Injection and Testing in JUnit 5.JPG

For the example above, we remark the following:
  1. The first test is repeated five times, and at each repetition it shows the display name, the current repetition number and the total number of repetitions (1).
  2. The second test is repeated five times, and at each repetition it shows the number of elements into the list (which is the current repetition number) and the fact that the set always has only one element (2).
  3. At the execution of each of the repeated second test, the repetition number is displayed, as it’s injected into the RepetitionInfo parameter (3).

The result of the execution of the previous tests is shown in figures 2 and 3.

Repetead Tests Dependency Injection and Testing in JUnit 5.JPG

Figure 2 The names of the repeated tests at the time of the execution

repeated tests .jpg

Figure 3 The messages shown into the console by the second repeated test

Interested in Java? Check out our trainings.

Catalin Tudose
Java and Web Technologies Expert

Share the knowledge

Still have questions?
Connect with us
Thank you.
Your request has been received.
Thank you!
The form has been submitted successfully.