JUnit 5 is a powerful and flexible testing framework in the Java ecosystem, widely used for unit testing Java applications. It introduces several modern features that simplify testing, making it a preferred choice for developers. One of its common features is the @RepeatedTest annotation, which is designed for running the same test multiple times. This feature helps test the stability of Java code, identify flaky tests, and ensure the overall robustness of applications.
In this article, we will learn the JUnit 5 @RepeatedTest annotation, and understand its syntax, and also we will do a step-by-step implementation to help developers and students easily understand and apply this concept in their Java projects.
Prerequisites:
Before proceeding, ensure the following:
- Java Development Kit (JDK): Use Java 8 or later.
- Build Management Tool: Maven or Gradle.
- Integrated Development Environment (IDE): Eclipse, IntelliJ IDEA, or any Java IDE.
- Basic Understanding of JUnit: Familiarity with writing unit tests.
@RepeatedTest in JUnit 5
The @RepeatedTest annotation in JUnit 5 is used to execute a test method multiple times. This is particularly useful to,
- Verify the stability of code under repeated executions.
- Identify flaky tests that may fail inconsistently.
- Test robustness for specific scenarios.
Syntax of @RepeatedTest
@RepeatedTest (value, name)
Parameters:
- value: It represents the number of times the test must execute repeatedly.
- name (optional): It represents the display name for every time the test executes.
Steps to Implement @RepeatedTest in JUnit 5
Step 1: Project Setup
Create a new Maven project using your preferred IDE (Here, we are using Eclipse IDE for Java and Web Developers. You may also use other platforms like IntelliJ, Spring suite tool, Spring Initializer, etc.)
- Go to the "file" menu and click new and navigate to "Spring Starters project". If you don't find the Spring Starters project immediately after "new", then click other and find "Spring Starters project".
- File > new > Spring Starters project.
Select Spring Starters project:
Name the project and configure the default options given if necessary.
Recommended requirements:
Project type: Maven
Packaging: Jar
Java Version: 8
Language: Java
- Make sure that, you have chosen the type as "Maven" and the version of Java should be at least 8.
- Add dependencies If you need any, otherwise, click "finish".
Step 2: Add Dependencies
Add the following JUnit Jupiter API dependency in your pom.xml file:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.10.0</version> <!-- Use the latest stable version -->
<scope>test</scope>
</dependency>
JUnit Jupiter API: The JUnit Jupiter API is the part of JUnit 5 framework which provides annotations, assertions, and other features for defining and running test cases and serves as a programming model for writing tests in Java. To add the JUnit Jupiter API in pom.xml file, copy and paste the above code.
Step 3: Create a Java Class for Testing
- Create a new package in the src/test/java named "project".
- Right-click on src/test/java > new > package.
Provide a name to the package. Here we are giving the name as "project".
- Inside the package, create a class Addition.java
- To create a class, right-click on package > new > class
Provide the class name:
Inside the Addition.java class write the following code:
Java
//Java code to demonstrate addition operation
package project;
public class Addition {
public int sum(int a, int b) {
return a + b;
}
}
Step 4: Write Test Cases with @RepeatedTest
Example 1: Simple Repeated Test
Create a test case in src/test/java under the same package (project).
Write the following test case to execute the sum method three times:
Java
package project;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.RepeatedTest;
class Testcase1 {
// Executes the test 3 times
@RepeatedTest(3)
public void testAddition() {
Addition addition = new Addition();
// Test data
int actual = addition.sum(2, 3);
int expected = 5;
// Assertion
assertEquals(actual, expected);
System.out.println("Test executed");
}
}
Steps to run the Test
To run the application, Go to project explorer > right click on your project > Run as > Spring Boot App.
Output:
JUnit view:
Console view:
Explanation:
In the above code snippet, the "Testcase1" is annotated with "@RepeatedTest()" along with the "value" as "3" representing that the test should execute 3 times. we have defined the "test1" method in which we have created the "addition" object for "Addition.java" and calculated the sum and stored in "actual" variable. We have asserted the result by comparing the "actual" and "expected" values with "assertEquals" method.
Example 2: Using Custom Display Name
Modify the @RepeatedTest annotation to include a custom name for each repetition.
Java
package project;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.RepeatedTest;
class Testcase2 {
@RepeatedTest(value=3, name="Test run {currentRepetition} of {totalRepetitions}")
public void test1() {
Addition addition = new Addition();
int actual = addition.sum(2, 3);
int expected = 5;
assertEquals(actual, expected);
System.out.println("Test executed");
}
}
Output:
JUnit view:
Console view:
Explanation:
In the above code snippet, the "Testcase2" is annotated with "@RepeatedTest()" along with the "value" as "3" and "name" as "Test run {currentRepetition} of {totalRepetitions}" representing that the test should execute 3 times and displaying the current and total repeatition values. we have defined the "test1" method in which we have created the "addition" object for "Addition.java" and calculated the sum and stored in "actual" variable. We have asserted the result by comparing the "actual" and "expected" values with "assertEquals" method.
Benifits of Using @RepeatedTest
- Keep Tests Independent: It ensure each test does not depend on the result of another test.
- Use Meaningful Assertions: It verify each test case provides useful validation.
- Avoid State Modification: It reset shared resources between test runs to avoid interference.
- Debug Flaky Tests: It uses @RepeatedTest to identify tests that fail inconsistently under certain conditions.
Similar Reads
JUnit 5 - @ParameterizedTest
Parameterized tests in JUnit 5 provide the ability to run the same test multiple times with different inputs, helping to improve code coverage and catch edge cases that might otherwise go unnoticed By automating test execution with multiple sets of input data, parameterized tests simplify validation
4 min read
JUnit â Ordered Tests
JUnit is a popular framework in the Java ecosystem designed for creating and executing automated tests. Although the framework encourages writing independent tests that can run in any order, there are scenarios where tests need to be executed in a specific order. This article explores how to order t
7 min read
JUnit 5 @Nested Test Classes
JUnit 5 introduced several powerful features to make testing in Java more flexible and expressive. One of these features is the @Nested test classes, which allows for better organization of test cases by logically grouping them inside an outer test class. This can be particularly useful when dealing
6 min read
JUnit 5 - Eclipse Test Templates
JUnit 5 simplifies the process of writing and executing test cases in Java applications. It offers enhanced support for modern Java features, increased extensibility, and a testing API that is more flexible and expressive. Test TemplatesA test template is a predefined format for writing test cases o
7 min read
JUnit 5 â Test LifeCycle
In the Java testing framework, JUnit 5 is the latest testing framework that introduces a robust test lifecycle that is managed through four primary annotations that are @BeforeAll, @BeforeEach, @AfterEach, and @AfterAll. We need to annotate each method with @Test annotation from the org.junit.jupite
5 min read
JUnit 5 â Test Reports in HTML
In this article, we will discuss how to view Test reports of JUnit 5 in HTML formats. By default, JUnit 5 produces test reports in the form of XML files but understanding XML files directly is not possible and we will need some other third-party tool to parse the XML and give us the information abou
4 min read
JUnit 5 - @TempDir
JUnit 5 is a popular framework for testing Java code, offering many useful features to make testing easier. One of these features is the @TempDir annotation, which helps manage temporary files and directories during tests. This article will explain how @TempDir works and how it can simplify your tes
6 min read
JUnit 5 â @Timeout
The @Timeout annotation in JUnit restricts the duration of test and lifecycle methods. It aids in ensuring that a test procedure is completed according to the planned timetable. TimeoutExceptions occur when the duration of the test method exceeds the specified limit. Any JUnit test or lifecycle meth
7 min read
JUnit 5 - @Tag
In todayâs software development world, having a solid testing strategy is essential for building reliable applications. JUnit 5, a popular testing framework for Java, helps us manage our tests more effectively with a feature called @Tag. This annotation allows us to label and filter our tests based
4 min read
JUnit 5 â Test Execution Order
In JUnit 5, the Test execution order is not in the order by default. Every Test is randomly executed one after the other. There is no compulsion that the test which is on top will be executed first and the test which is in bottom will be executed last. So, the order of execution of test cases is unp
4 min read