JUnit 4:如何在规则中获取测试名称?



JUnit 4:如何在Rule中获取测试名称?

public class MyRule extends ExternalResource {
@Before
public void before() {
// how to get the test method name to be run?
}
}

如果您只需要一个带有测试名称的@Rule,请不要重新设置轮子,只需使用内置TestName@Rule即可。

如果您尝试构建自己的规则来向其添加一些逻辑,请考虑扩展它。如果这也不是一个选项,你可以复制它的实现。

要回答评论中的问题,像任何其他TestRule一样,ExternalResouce也有apply(Statement, Description)方法。您可以通过重写它来为其添加功能,只需确保调用 super 方法,以免破坏ExternalResource功能:

public class MyRule extends ExternalResource {
private String testName;
@Override
public Statement apply(Statement base, Description description) {
// Store the test name
testName = description.getMethodName();
return super.apply(base, description);
}
public void before() {
// Use it in the before method
System.out.println("Test name is " + testName);
}
}

最新更新