测试失败后如何从 运行 停止 TestNG

How to stop TestNG from running after a test fail

我正在尝试在 TestNG 中编写一个测试方法,在它失败后 - 整个测试套件将停止 运行。

@Test
public void stopTestingIfThisFailed() throws Exception
{
    someTestStesp();
    if (softAsserter.isOneFailed()) {
        asserter.fail("stopTestingIfThisFailed test Failed");
        throw new Exception("Test can't continue, fail here!");
    }
}

正在抛出异常,但其他测试方法是运行。

如何解决?

如果您从 @BeforeSuite 设置方法中抛出特定异常 SkipException,它就会起作用。

见(可能是骗子)

如果你想从任意测试来做,似乎没有框架机制。但是您始终可以翻转一个标志,并在 @BeforeTest 设置方法中检查该标志。在你跳到那个之前,也许想一想你是否可以在整个套件运行之前检查一次,然后就在那里中止(即 @BeforeSuite)。

您可以在其他测试方法中使用 dependsOnMethodsdependsOnGroups 注释参数:

@Test(dependsOnMethods = {"stopTestingIfThisFailed"})
public void testAnotherTestMehtod()  {

}

JavaDoc of the dependsOnMethods parameter:

The list of methods this method depends on. There is no guarantee on the order on which the methods depended upon will be run, but you are guaranteed that all these methods will be run before the test method that contains this annotation is run. Furthermore, if any of these methods was not a SUCCESS, this test method will not be run and will be flagged as a SKIP. If some of these methods have been overloaded, all the overloaded versions will be run.

https://testng.org/doc/documentation-main.html#dependent-methods

这取决于您的期望(TestNG 对此没有直接支持)。您可以创建 ShowStopperException 并在 @Test 中抛出,然后在您的 ITestListener 实现 (see docs) 中,当您在结果中发现此异常时可以调用 System.exit(1 (or whatever number)) 但是不会有报告,一般来说这不是好的做法。第二个选择是有一些基础 class 它是所有测试 classes 的父级和一些上下文变量将处理 ShowStopperException in @BeforeMethod in parent class 和throw SkipException 所以工作流程可以是这样的:

test passed
test passed
showstopper exception in some test
test skipped
test skipped
test skipped
...

我这样解决了这个问题:在一个不能失败的测试失败后 - 我正在将数据写入一个临时文本文件。

稍后,在下一个测试中,我在 @BeforeClass 中添加了代码,用于检查前面提到的文本文件中的数据。如果发现一个显示停止程序,我将终止当前进程。

如果 "can't" 失败的测试实际上失败了:

 public static void saveShowStopper() {

    try {
        General.createFile("ShowStopper","tempShowStopper.txt");
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

@BeforeClass 验证码:

@BeforeClass(alwaysRun = true)
public void beforeClass(ITestContext testContext, @Optional String step, @Optional String suiteLoopData,
        @Optional String group) throws Exception
{
    boolean wasShowStopperFound = APIUtils.loadShowStopper();
    if (wasShowStopperFound){
        Thread.currentThread().interrupt();
        return;
    }
}