[英]jUnit ignore @Test methods from base class
假设我有一个名为testFixtureA
的测试类,它有几个方法testA
、 testB
、 testC
等,每个方法都有@Test
注释。
现在假设我将testFixtureA
子类化到名为testFixtureAB
的类中,并且我不覆盖任何内容。 testFixtureAB
目前是空的。
当我从testFixtureAB
运行测试时,方法testA
, testB
和testC
由测试运行器执行,因为测试运行器不区分来自类和基类的测试方法。
如何强制测试运行器从基类中省略测试?
我不会覆盖任何东西。 testFixtureAB 目前为空
这就是你的答案。 如果您不想从主类运行 testB,请覆盖它:
public class testFixtureAB extends testFixtureA {
@Override
public void testB() {}
}
重组你的测试类。
实现一些类很容易实现:
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);
}
}
在 Junit 5 中,您可以将基类作为抽象类并使用具体类对其进行扩展。
当您在 IDE 中运行抽象时,您的子类将被执行。
在最新的 JUnit 中,您可以在子类上使用 @Rule 注释来检查测试名称并拦截测试运行以动态忽略测试。 但我建议@Bozho 的想法更好——你需要这样做的事实表明一个更大的问题可能表明继承在这里不是正确的解决方案。
我知道,这不是答案...
考虑扩展具体测试类的原因。 你这样做是重复的测试方法。
如果您在测试之间共享代码,请考虑使用助手和夹具设置方法或测试助手类编写基本测试类。
如果要运行测试,请尝试使用套件和类别组织测试。
如果您想为同一测试套件的不同配置执行相同的测试怎么办?
例如,假设您有一个带有 test1、test2 和 test3 方法的 A 类,它们命中嵌入式数据库,然后您想为每个嵌入式供应商(H2、HyperSQL 等)创建单独的“setUp”和“tearDown”,但运行相同的测试每一个人。
我想扩展一个包含这些测试方法的类并在子类中配置它。 我的问题是超类不应该被认为有资格成为测试运行者。 当测试运行程序执行超类并且没有找到相应的设置和拆卸方法时,就会出现问题,它会崩溃:(
在基础测试类的@Test 方法中:
assumeTrue(getClass().equals(BaseClassTest.class));
它将忽略子类测试中的那些,但不会完全将它们排除在外。
如果出于某种原因您需要两个 JUnit 类来实现相同的功能,对我来说最好的方法是:
TestFixture
中。TestFixtureA
和TestFixtureB
这样你就不会有重复的代码,也不会重复运行。
我遇到了一个类似的问题,我有一个通用的抽象基类 TestBase 和 2 个扩展基类的子类 TestA、TestB。 我希望 TestBase 中的所有测试都为 TestA 运行,但为 TestB 跳过一些测试。 您可以使用 JUnit 注释Nested
和Disabled
将基类中的测试分组到类别中,然后启用对整个测试类别的完全禁用。
public class TestB extends TestBase {
// disable entire suite of inherited tests
// from the nested class declared on the parent
@Nested
@Disabled
public class ComponentCTests {}
}
public abstract class TestBase {
@Nested
public class ComponentCTests {
@Test
public void testSomething() {
// test something
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.