Sunday 15 August 2021

Junit5: RepetitionInfo: Retrieve information about current repetition

If a method parameter in a @RepeatedTest, @BeforeEach, or @AfterEach method is of type RepetitionInfo, the RepetitionInfoParameterResolver will supply an instance of RepetitionInfo. RepetitionInfo can then be used to retrieve information about the current repetition and the total number of repetitions for the corresponding @RepeatedTest.

 

RepetitionInfoDemo.java

package com.sample.app;

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

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.RepetitionInfo;

public class RepetitionInfoDemo {
	
	private static void printRepetitionInfo(RepetitionInfo repetitionInfo) {
		int currentRepetition = repetitionInfo.getCurrentRepetition();
		int totalRepetitions = repetitionInfo.getTotalRepetitions();
		System.out.println("currentRepetition : " + currentRepetition + " , " + "totalRepetitions : " + totalRepetitions);
	}
	
	@BeforeEach
	public void setup(RepetitionInfo repetitionInfo) {
		System.out.println("\nInside Setup method");
		printRepetitionInfo(repetitionInfo);
	}
	
	@DisplayName("TestCase1")
	@RepeatedTest(value = 3, name = "{displayName} {currentRepetition}/{totalRepetitions}")
	void test1(RepetitionInfo repetitionInfo) {
		System.out.println("Inside test1 method");
		printRepetitionInfo(repetitionInfo);
		assertTrue(true);
	}
	
	@AfterEach
	public void cleanup(RepetitionInfo repetitionInfo) {
		System.out.println("Inside cleanup method");
		printRepetitionInfo(repetitionInfo);
	}
	


}

 

When you ran above test, you will see below messages in console.

Inside Setup method
currentRepetition : 1 , totalRepetitions : 3
Inside test1 method
currentRepetition : 1 , totalRepetitions : 3
Inside cleanup method
currentRepetition : 1 , totalRepetitions : 3

Inside Setup method
currentRepetition : 2 , totalRepetitions : 3
Inside test1 method
currentRepetition : 2 , totalRepetitions : 3
Inside cleanup method
currentRepetition : 2 , totalRepetitions : 3

Inside Setup method
currentRepetition : 3 , totalRepetitions : 3
Inside test1 method
currentRepetition : 3 , totalRepetitions : 3
Inside cleanup method
currentRepetition : 3 , totalRepetitions : 3

 


 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment