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

2022-09-01 07:40:32

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

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


答案 1

编写可重用代码(而不是从中继承)的 JUnit 方法是 Rules。

查看 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_CODEAFTER_CODE

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

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

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

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

呵呵


答案 2

如果该方法是某种实用工具,则使用静态方法将其分离到其他类中,并在@BeforeClass中调用该方法。

我强调这样一个事实,即不要仅仅因为继承解决了你的问题就使用它,在这样做时使用它可以在你的类层次结构中创造意义。


推荐