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

晴天 :

JUnit 4:如何在内获取测试名称Rule例如,

public class MyRule extends ExternalResource {

    @Before
    public void before() {
        // how to get the test method name to be run?
    }
}
Mureinik:

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

如果您试图建立自己的规则以增加一些逻辑,请考虑对其进行扩展。如果这也不是一个选择,则可以复制它的实现

要像其他评论一样回答评论中的问题TestRuleExternalResouce也有一个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);
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章