What is the equivalent of TestName rule in JUnit 5?
Declare a parameter of type TestInfo
in your test method and JUnit will automatically supply an instance of that for the method:
@Test
void getTestInfo(TestInfo testInfo) { // Automatically injected
System.out.println(testInfo.getDisplayName());
System.out.println(testInfo.getTestMethod());
System.out.println(testInfo.getTestClass());
System.out.println(testInfo.getTags());
}
You can get test method name (and more) from the TestInfo
instance as shown above.
In addition to what is written about injecting TestInfo
to test method it is also possible to inject TestInfo
to methods annotated with @BeforeEach
and @AfterEach
which might be useful sometimes:
@BeforeEach
void setUp(TestInfo testInfo) {
log.info(String.format("test started: %s", testInfo.getDisplayName());
}
@AfterEach
void tearDown(TestInfo testInfo) {
log.info(String.format("test finished: %s", testInfo.getDisplayName());
}