jUnit忽略基类中的@Test方法

时间:2010-02-05 12:16:34

标签: java inheritance junit

假设我有一个名为testFixtureA的测试类,其中有多个方法testAtestBtestC等,每个方法都带有@Test注释。

现在让我说我将testFixtureA子类化为名为testFixtureAB的类,我不会覆盖任何内容。 testFixtureAB现在是空的。

当我从testFixtureAB运行测试时,方法testAtestBtestC由测试运行器执行,因为测试运行器不区分测试方法与类和基类。

如何强制测试运行器从基类中省略测试?

10 个答案:

答案 0 :(得分:22)

  

我不会覆盖任何东西。   testFixtureAB现在是空的

有你的答案。如果您不想从主类运行testB,请覆盖它:

public class testFixtureAB extends testFixtureA {
   @Override
   public void testB() {}
}

答案 1 :(得分:20)

重组您的测试类。

  • 如果您不想使用基类中的测试,则不要扩展它
  • 如果您需要基类中的其他功能,请将该类拆分为两个 - 测试和其他功能

答案 2 :(得分:11)

忽略整个基类:

@Ignore
class BaseClass {
   // ...
}

check out this example

答案 3 :(得分:8)

实现几个类很容易实现:

  • 创建自己的TestRunner
  • 创建类似@IgnoreInheritedTests
  • 的注释
  • 创建一个扩展org.junit.runner.manipulation.Filter
  • 的类

在过滤器类上:

public class InheritedTestsFilter extends Filter {

    @Override
    public boolean shouldRun(Description description) {
        Class<?> clazz = description.getTestClass();
        String methodName = description.getMethodName();
        if (clazz.isAnnotationPresent(IgnoreInheritedTests.class)) {
            try {
                return clazz.getDeclaredMethod(methodName) != null;
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }

    @Override
    public String describe() {
        // TODO Auto-generated method stub
        return null;
    }

}

在您的自定义选手上:

 /**
 * @param klass
 * @throws InitializationError
 * @since
 */
public CustomBaseRunner(Class<?> klass) throws InitializationError {
    super(klass);
    try {
        this.filter(new InheritedTestsFilter());
    } catch (NoTestsRemainException e) {
        throw new IllegalStateException("class should contain at least one runnable test", e);
    }
}

答案 4 :(得分:1)

在最新的JUnit中,您可以使用子类上的@Rule注释来检查测试名称并拦截测试运行以动态忽略测试。但我建议@Bozho的想法是更好的 - 你需要这样做的事实表明一个更大的问题可能表明继承在这里不是正确的解决方案。

答案 5 :(得分:1)

我知道,这不是答案......

考虑扩展具体测试类的原因。你这样做会重复测试方法。

如果您在测试之间共享代码,请考虑使用helper and fixture setup methodstest helper class编写基本测试类。

如果要运行测试,请尝试使用套件和categories组织测试。

答案 6 :(得分:1)

如果要对同一测试套件的不同配置执行相同的测试,该怎么办?

例如,假设你有A类,其中test1,test2和test3方法遇到嵌入式数据库,那么你想为每个嵌入式供应商(H2,HyperSQL等)创建单独的“setUp”和“tearDown”,但是运行对每一个进行相同的测试。

我想扩展一个包含这些测试方法的类,并在子类中配置它。我的问题是超级班不应该被认为有资格参加测试跑步者。当测试运行器执行超类并且没有找到相应的设置和拆卸方法时会出现问题,它会崩溃:(

答案 7 :(得分:1)

在Junit 5中,您可以将基类作为抽象类,并使用具体类对其进行扩展。

在IDE中运行摘要时,将改为执行子类。

答案 8 :(得分:0)

在基础测试类'@Test方法:

assumeTrue(getClass().equals(BaseClassTest.class));

它将忽略子类测试中的那些但不完全将它们排除在外。

答案 9 :(得分:0)

如果出于某种原因您需要两个JUnit类来实现相同的功能,那么对我来说最好的方法是:

  • 将通用代码放入仅包含常量和模拟服务的父类{ user_record( id:"b8faaf26-c8a6-3560-8357-f789f3325b0c", tenantReference:"lightcoral70" ) { id, tenant_reference, roles, custom_attributes{ fred } } 中。
  • 创建两个子类:TestFixtureTestFixtureA

这样,您将不会重复代码,也不会重复运行。

相关问题