如何在 JUnit 5 的“@BeforeEach”方法中打印 "to be executed" @Test 方法的名称?

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

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

@BeforeEach 方法中声明一个 TestInfo 参数。 JUnit Jupiter 将在运行时注入它的一个实例,其中包含与 "currently executed test".

相关的所有可用信息

例如像这样:

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

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