JUnit 4:如何获取规则
内的测试名称?例如,
public class MyRule extends ExternalResource {
@Before
public void before() {
// how to get the test method name to be run?
}
}
最佳答案
如果您只需要一个带有测试名称的@Rule
,请不要重新投入轮子,只需使用内置的 TestName
@Rule
。
如果您尝试构建自己的规则并为其添加一些逻辑,请考虑扩展它。如果这也不是一个选项,您可以复制它的 implementation .
为了回答评论中的问题,与任何其他 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);
}
}
关于java - JUnit 4 : how to get test name inside a Rule?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59588850/