I try to write my own JUnit 5 extension, providing some simple information about test duration. I also want to print out the repetition information but how can I access these informations in the extension? Are there any simple ways instead of reflection or writing and parsing the numbers to the display name?
simple example:
@ExtendWith(TimingExtension.class)
public class MyTestClass {
@RepeatedTest(value = 5, name = "{currentRepetition}/{totalRepetitions}")
public void myTest(TestInfo testInfo, RepetitionInfo repInfo) {
// do some work here...
}
}
public class TimingExtension implements AfterTestExecutionCallback {
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
if(context.getRequiredTestMethod().getDeclaredAnnotation(RepeatedTest.class) != null) {
System.out.println("This was test X of Y"); // how to get currentRepetition and totalRepetitions here?
}
}
}
Unfortunately there is no support for parameter injection in extensions. It's only one way. So in order to get RepetitionInfo
in your TimingExtension
you have to set it.
First you need to use @RegisterExtension
e.g.
public class MyTestClass {
@RegisterExtension
TimingExtension timingExt = new TimingExtension();
@RepeatedTest(value = 5, name = "{currentRepetition}/{totalRepetitions}")
public void myTest(TestInfo testInfo, RepetitionInfo repInfo) {
timingExt.setRepetitionInfo(repInfo);
// do some work here...
}
}
public class TimingExtension implements AfterTestExecutionCallback {
private RepetitionInfo repInfo;
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
if (context.getRequiredTestMethod().getDeclaredAnnotation(RepeatedTest.class) != null && repInfo != null) {
System.out.println(String.format("This was test %d of %d", repInfo.getCurrentRepetition(), repInfo.getTotalRepetitions()))
repInfo = null;
}
}
public void setRepetitionInfo(RepetitionInfo repInfo) {
this.repInfo = repInfo;
}
}