我在 JUnit 中有许多测试用例。它们都需要在它们的 @BeforeClass
静态方法中执行相同的代码。这是一个代码重复,我正试图摆脱它。一种肮脏的做法是通过继承。 JUnit 中是否还有其他机制可能有所帮助?
PS。我写了这篇关于这个主题的博客文章:http://www.yegor256.com/2015/05/25/unit-test-scaffolding.html
最佳答案
编写可重用代码(而不是从它继承)的 JUnit 方法是规则。
见 https://github.com/junit-team/junit/wiki/Rules
这是一个愚蠢的示例,但你会明白的。
import org.junit.rules.TestRule;
import org.junit.runners.model.Statement;
import org.junit.runner.Description;
public class MyTestRule implements TestRule {
@Override
public Statement apply(final Statement statement, Description description) {
return new Statement() {
public void evaluate() throws Throwable {
// Here is BEFORE_CODE
try {
statement.evaluate();
} finally {
// Here is AFTER_CODE
}
}
};
}
}
然后您可以像这样使用您的 TestRule:
import org.junit.Rule;
public class MyTest {
@Rule
public MyTestRule myRule = new MyTestRule();
}
BEFORE_CODE 和 AFTER_CODE 然后将围绕您的每个测试方法执行。
如果您只需要在每个类中运行一次代码,请将您的 TestRule 用作@ClassRule:
import org.junit.ClassRule;
public class MyTest {
@ClassRule
public static MyTestRule myRule = new MyTestRule();
}
现在,BEFORE_CODE
和 AFTER_CODE
将围绕您的每个测试类执行。
@Rule字段不是静态的,@ClassRule字段是。
@ClassRule 也可以在套件中声明。
请注意,您可以在单个测试类中声明多个规则,这就是您在测试套件、测试类和测试方法级别组成测试生命周期的方式。
规则是您在测试类中实例化的对象(静态或非静态)。如果需要,您可以添加构造函数参数。
HTH
关于java - 如何避免 JUnit 测试用例中的继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6715281/