gpt4 book ai didi

java - JUnit 4 : how to get test name inside a Rule?

转载 作者:行者123 更新时间:2023-11-30 01:42:06 33 4
gpt4 key购买 nike

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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com