java - 如果特定测试失败则停止 JUnit 套件

标签 java junit

我有一个 JUnit 测试套件,形式如下:

@RunWith(Suite.class)
@Suite.SuiteClasses( { xx.class, yy.cass })

public class AllTests {

public static Test suite() {
    TestSuite suite = new TestSuite(AllTests.class.getName());
    //$JUnit-BEGIN$

    //$JUnit-END$
    return suite;
}
}

然后像这样调用原始测试:

public class xxx {

@Test
public void test () throws {
    ...

我有一种情况,如果第一个测试出现错误或失败,我想停止其余测试套件的运行。但是其他的错误/失败是可以的,套件应该完成尽可能多的其他测试。基本上,第一个测试失败表明运行其余测试不安全。

这可能吗?

最佳答案

首先你需要junit RunListener:

import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;

public class FailureListener extends RunListener {

    private RunNotifier runNotifier;

    public FailureListener(RunNotifier runNotifier) {
        super();
        this.runNotifier=runNotifier;
    }

    @Override
    public void testFailure(Failure failure) throws Exception {
        super.testFailure(failure);
        this.runNotifier.pleaseStop();
    }
}

然后准备一个套件:

public class StopOnFailureSuite extends Suite {

    public StopOnFailureSuite(Class<?> klass, Class<?>[] suiteClasses) throws InitializationError {
        super(klass, suiteClasses);
    }

    public StopOnFailureSuite(Class<?> klass) throws InitializationError {
        super(klass, klass.getAnnotation(SuiteClasses.class).value());
    }

    @Override
    public void run(RunNotifier runNotifier) {
        runNotifier.addListener(new FailureListener(runNotifier));
        super.run(runNotifier);
    }
}

然后运行你的套件:

@RunWith(StopOnFailureSuite.class)
@Suite.SuiteClasses({
    FirstTestClass.class,
    SecondTestClass.class,
    ...
})

关于java - 如果特定测试失败则停止 JUnit 套件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10036894/

相关文章:

junit - 如何使用JUnit4以编程方式执行测试套件?

java - java中的字符串逆向混淆 - String - StringBuilder

java - Resteasy异常 "No type information to extract entity with, use other getEntity() methods"

java - 如何在单元测试中处理 session 变量

java - 参数匹配器的使用无效!预期 0 个匹配器,记录 1 个

java - 模拟 JUnit 构造函数的最佳方法是什么?

java - Play framework 2.4 表单填写不起作用

java - Firefox在Struts应用程序中剪切名称中包含空格的文件

java - Realm 迁移重复值

java - 如何将我自己的 Android 应用程序项目导入到 IBM Bluemix 中?