如何在JUnit测试用例中避免继承?

yeg*_*256 34 java junit

我在JUnit中有很多测试用例.所有这些都需要在@BeforeClass静态方法中执行相同的代码.这是代码重复,我试图摆脱它.这样做的一种肮脏方式是继承.JUnit中是否还有其他机制可能会有所帮助?

PS.我写了这篇关于这个主题的博客文章:http://www.yegor256.com/2015/05/25/unit-test-scaffolding.html

esk*_*tos 39

构建可重用代码(而不是从中继承)的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
        }
      }
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样使用TestRule:

import org.junit.Rule;

public class MyTest {
    @Rule
    public MyTestRule myRule = new MyTestRule();
}
Run Code Online (Sandbox Code Playgroud)

然后将围绕每个测试方法执行BEFORE_CODE和AFTER_CODE.

如果您只需要为每个类运行一次代码,请将TestRule用作@ClassRule:

import org.junit.ClassRule;

public class MyTest {
    @ClassRule
    public static MyTestRule myRule = new MyTestRule();
}
Run Code Online (Sandbox Code Playgroud)

现在,BEFORE_CODEAFTER_CODE将围绕每个测试类的执行.

@Rule字段不是静态的,@ ClassRule字段是.

@ClassRule也可以在套件中声明.

请注意,您可以在单个测试类中声明多个规则,这就是在测试套件,测试类和测试方法级别组成测试生命周期的方式.

规则是您在测试类中实例化的对象(静态或非静态).如果需要,您可以添加构造函数参数.

HTH