Ashwin Kumar
Ashwin Kumar

Reputation: 118

How to print the "to be executed" @Test method's name in "@BeforeEach" method in JUnit 5?

I understand we can do this in JUnit 4 using @Rule and TestName however am using JUnit 5 (Jupiter) and am struggling to find a way to print the test methods(to be executed) name in @BeforeEach method.

Upvotes: 8

Views: 5211

Answers (1)

Sormuras
Sormuras

Reputation: 9059

Declare a TestInfo parameter in your @BeforeEach method. JUnit Jupiter will inject an instance of it at runtime containing all the available information related to the "currently executed test".

For example like this:

@BeforeEach
void init(TestInfo testInfo) {
    String displayName = testInfo.getDisplayName();
    String methodName = testInfo.getTestMethod().orElseThrow().getName();
    // ...
}

For more details see https://junit.org/junit5/docs/current/user-guide/#writing-tests-dependency-injection

Upvotes: 22

Related Questions