如何在 JUnit 5 的“@BeforeEach”方法中打印“待执行”@Test 方法的名称?

Ash*_*mar 3 junit5

我知道我们可以在 JUnit 4 中使用@RuleTestName但是我正在使用 JUnit 5(Jupiter)并且正在努力寻找一种方法来打印方法中的测试方法(待执行)名称@BeforeEach

Sor*_*ras 9

TestInfo在你的@BeforeEach方法中声明一个参数。JUnit Jupiter 将在运行时注入它的一个实例,其中包含与“当前执行的测试”相关的所有可用信息。

例如像这样:

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

有关更多详细信息,请参阅https://junit.org/junit5/docs/current/user-guide/#writing-tests-dependency-injection