x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    JUnit 5 Repeat Tests

    If you want to repeat a JUnit test, it can be done using @RepeatedTest annotation. It is useful in scenario where conditions change after a JUnit test is executed. Below are few examples that show how to use @RepeatedTest annotation in JUnit 5.

    1. Repeat JUnit 5 test n number of times using @RepeatedTest annotation

    import static org.junit.jupiter.api.Assertions.assertEquals;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.RepeatedTest;import calculator.Calculator;public class RepeatedTests {    @RepeatedTest(value = 3)    @DisplayName("Test divide operation")    void testDivideNumber() {        Calculator calculator = new Calculator();        assertEquals(3, calculator.divide(6, 2));    }}

    2. Repeat test using @RepeatedTest annotation with "name" attribute

    You can use "name" attibute to print current iteration count and total repetition count.

    @RepeatedTest(value = 3, name = "{displayName} - repetition number {currentRepetition}/{totalRepetitions}")@DisplayName("Test subtract operation")void testSubtractNumber() {    Calculator calculator = new Calculator();    assertEquals(3, calculator.subtract(5, 2));}

    3. Repeat test with @RepetitionInfo annotation

    @RepetitionInfo annotation allows to access the current iteration count and total repetition count.

    import static org.junit.jupiter.api.Assertions.assertEquals;import java.util.HashMap;import java.util.Map;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.RepeatedTest;import org.junit.jupiter.api.RepetitionInfo;import calculator.Calculator;public class RepeatedTests {        private Map<Integer, Double> map = new HashMap<>();        @BeforeEach    public void setup() {        map.put(1, 3.0);        map.put(2, 1.0);        map.put(3, 1.0);    }        @RepeatedTest(value = 3)    @DisplayName("Test divide operation")    public void testDivideNumber(RepetitionInfo repetitionInfo) {        System.out.format("current repetition %s, total repetetions %s \n",            repetitionInfo.getCurrentRepetition(), repetitionInfo.getTotalRepetitions());        Calculator calculator = new Calculator();        assertEquals(map.get(repetitionInfo.getCurrentRepetition()),             calculator.divide(repetitionInfo.getTotalRepetitions(),            repetitionInfo.getCurrentRepetition()));    }}

    Maven Build




















    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This