In this post under JUnit, I will show with example the purpose and how to use JUnit 5’s “RepeatedTest” annotation.
The “RepeatedTest” annotation is applied on a method.
Once applied it indicates the JUnit that it has repeat testing of annotated method a specified number of times.
Below is the snapshot showing how to use it
@RepeatedTest(value = 10)
public void testMethod() {
...
}
In the above code snippet, 10 represents the number of times the annotated method has to be repeated. We pass this value as annotation argument.
Each execution of the repeated test is similar to the execution of a regular @Test method with full support for the same lifecycle callbacks and extensions.
Below is the complete main code for your reference.
Main class
1 package package19;
2
3 import org.junit.jupiter.api.RepeatedTest;
4 import java.util.Random;
5
6 import static org.junit.jupiter.api.Assertions.assertTrue;
7
8 public class JavaRandomTest {
9 private Random random = new Random();
10
11 @RepeatedTest(value = 10)
12 public void testJavaRandom() {
13 int result = random.nextInt(12);
14 assertTrue(result < 12);
15 }
16 }
In the above code, I am testing the Java “Random” class. Especially I am testing “nextInt” method of “Random” class.
As you can see, at line 11, I have applied the annotation “RepeatedTest” with a value of “10”. So this declaration is instructing the JUnit to execute the annotated method 10 times.
During each execution of “testJavaRandom” method, I am asserting that value returned by “nextInt” is always below the upper limit 12.
In this way we can repeat method execution for a specific number of times.