JUnit 5 中的 TestName 规则等效于什么?

What is the equivalent of TestName rule in JUnit 5?

如何获取 JUnit 5 中测试方法的名称?

在您的测试方法中声明类型为 TestInfo 的参数,并为方法声明类型为 JUnit will automatically supply an instance 的参数:

@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());
}

您可以从 TestInfo 实例中获取测试方法名称(以及更多),如上所示。

除了关于将 TestInfo 注入测试方法的内容之外,还可以将 TestInfo 注入带有 @BeforeEach@AfterEach 注释的方法,这可能是有时有用:

@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());
}

在 JUnit 4 中尽可能使测试名称全局可用的替代方法是使用 TestInfo 接口在设置方法中自己填充功能。

来自JUnit documentation on "Dependency Injection for Constructors and Methods"

The TestInfo can then be used to retrieve information about the current container or test such as the display name, the test class, the test method, and associated tags.

这里我们利用了这样一个事实,即 built-in 解析器将提供一个 TestInfo 对应于当前容器或测试的实例作为类型 TestInfo 参数的值给注释的方法作为生命周期钩子(这里我们使用 @BeforeEach)。

import org.junit.jupiter.api.TestInfo;

public class MyTestClass {
  String displayName;

  @BeforeEach
  void setUp(TestInfo testInfo) {
    displayName = testInfo.getDisplayName();
    // ... the rest of your setup
  }
}

例如,这使您能够在其他 non-test 方法(例如各种实用程序方法)中引用当前测试名称,而不必将测试名称作为参数包含在初始测试方法的每个函数调用中那个实用方法。

您可以对有关当前容器或测试的其他信息执行相同的操作。

似乎唯一的缺点是:

  • 无法创建实例变量final,因为它是动态设置的
  • 可能会污染您的设置代码

作为参考,下面是 TestName-Rule 在 JUnit 4 中的实现方式:

public class MyTestClass {
  @Rule
  public final TestName name = new TestName();
}