Repeated Tests

Learn repeated tests in JUnit 5.

We'll cover the following

JUnit 5 allows us to repeat tests a specific number of times using the @RepeatedTest annotation.

This functionality is useful whenever the given test case has some randomness to it. For example, when we want to verify if a test behaves consistently between two executions, this is a good time to use it.

Usage

The @RepeatedTest(10) annotation refers to the number of times—10—the test will repeat.In addition to the number of repetitions, this annotation takes a custom display name for each repetition via the name attribute.

We can customize the name attribute for each repetition using the following placeholders:

  • {displayName} displays the name of the method with @RepeatedTest.
  • {currentRepetition} provides the current repetition number.
  • {totalRepetitions} provides the total number of repetitions.

Example

The code below demonstrates the usage of repeated tests.

Get hands-on with 1400+ tech skills courses.