Tuesday, 13 July 2021

Junit5: RepeatedTest: Repeat test given number of times

@RepeatedTest is used to signal that the annotated method is a test template method that should be repeated a specified number of times with a configurable display name.

 

RepeatedTest1.java

package com.sample.app;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.RepeatedTest;

public class RepeatedTest1 {
  
  @RepeatedTest(3)
  void test1() {
    assertTrue(true);
  }

}

 

Run above class, you will see that the test is executed thrice.

 


 

In addition to specify number of repetitions, you can configure custom display name for each repetition Using 'name' attribute.

 

Display name can be composed of a combination of static text and dynamic placeholders. Right now, following placeholders supported.

 

a.   {displayName} : Display Name of @RepeatedTest method.

b.   {currentRepetition} : Placeholder for the current repetition count of a @RepeatedTest method

c.    {totalRepetitions} : Placeholder for the total number of repetitions of a @RepeatedTest method

 

Apart from placeholders, @RepeatedTest annotation support following patterns.

a.   LONG_DISPLAY_NAME: Long display name pattern for a repeated test: "{displayName} :: repetition {currentRepetition} of {totalRepetitions}"

 

String LONG_DISPLAY_NAME = DISPLAY_NAME_PLACEHOLDER + " :: " + SHORT_DISPLAY_NAME;

 

b.   SHORT_DISPLAY_NAME: Short display name pattern for a repeated test: "repetition {currentRepetition} of {totalRepetitions}"

 

String SHORT_DISPLAY_NAME = "repetition " + CURRENT_REPETITION_PLACEHOLDER + " of " + TOTAL_REPETITIONS_PLACEHOLDER;

 

Note:

If you do not specify a DisplayName for the test method, it takes method name by default.

 

Let's see it with an example.

 

RepeatedTest2.java

package com.sample.app;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;

public class RepeatedTest2 {

  @DisplayName("TestCase1")
  @RepeatedTest(value = 3, name = "{displayName} {currentRepetition}/{totalRepetitions}")
  void test1() {
    assertTrue(true);
  }

  @DisplayName("TestCase2")
  @RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME)
  void test2() {
    assertTrue(true);
  }

  @RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)
  void test3() {
    assertTrue(true);
  }
}


Run above test, you will see that display names in junit window.




 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment