Open In App

JUnit 5 – @RepeatedTest

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
Project-Creation


Select Spring Starters project:

Wizard-Window


Name the project and configure the default options given if necessary.

Project-Metadata


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".
Starter-Dependencies


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.
Project-Creation-for-Application


Provide a name to the package. Here we are giving the name as "project".

Creation-of-Java-package


  • Inside the package, create a class Addition.java
  • To create a class, right-click on package > new > class
Class-Creation


Provide the class name:

Window-for-Class-Creation


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).

Test-Case-Creation


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.

Run-Window


Output:

JUnit view:

JUnit-View


Console 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:

JUnit-View-1


Console view:

Console-View-1

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.

Next Article

Similar Reads