In JUnit 5 TestInfo
acts as a drop-in replacement for the TestName rule from JUnit 4.
From the documentation :
TestInfo is used to inject information about the current test or
container into to @Test, @RepeatedTest, @ParameterizedTest,
@TestFactory, @BeforeEach, @AfterEach, @BeforeAll, and @AfterAll
methods.
To retrieve the method name of the current executed test, you have two options : String TestInfo.getDisplayName()
and
Method TestInfo.getTestMethod()
.
To retrieve only the name of the current test method TestInfo.getDisplayName()
may not be enough as the test method default display name is methodName(TypeArg1, TypeArg2, ... TypeArg3)
.
Duplicating method names in @DisplayName("..")
is not necessary a good idea.
As alternative you could use
TestInfo.getTestMethod()
that returns a Optional<Method>
object.
If the retrieval method is used inside a test method, you don't even need to test the Optional
wrapped value.
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.Test;
@Test
void doThat(TestInfo testInfo) throws Exception {
Assertions.assertEquals("doThat(TestInfo)",testInfo.getDisplayName());
Assertions.assertEquals("doThat",testInfo.getTestMethod().get().getName());
}