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

时间:2019-05-20 12:09:21

标签: java selenium testng

我正在尝试在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!");
    }
}

正在引发异常,但其他测试方法正在运行。

如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

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

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

}

JavaDoc of the dependsOnMethods parameter

  

此方法所依赖的方法列表。不能保证所依赖的方法的运行顺序,但是可以保证所有这些方法都将在包含此批注的测试方法运行之前运行。此外,如果这些方法中的任何一个都不是SUCCESS,则该测试方法将不会运行,并将被标记为SKIP 。如果其中某些方法已重载,则将运行所有重载的版本。

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

答案 1 :(得分:1)

这取决于您的期望(TestNG中对此没有直接支持)。您可以创建ShowStopperException并抛出到@Test中,然后在您的ITestListener实现(see docs)中找到结果后调用System.exit(1 (or whatever number)),但是不会有任何报告,一般来说这不是一个好习惯。第二种选择是拥有一些基类,该基类是所有测试类的父类,还有一些上下文变量,它将处理父类中ShowStopperException中的@BeforeMethod并抛出SkipException,因此工作流可以像这样: / p>

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

答案 2 :(得分:0)

我解决了这样的问题:必须通过的测试失败后-我正在将数据写入临时文本文件。

稍后,在下一个测试中,我在@BeforeClass中添加了代码,用于检查前面提到的文本文件中的数据。如果找到放映塞,我正在杀死当前进程。

如果测试“不能”失败实际上会失败:

 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;
    }
}

答案 3 :(得分:-1)

如果您通过SkipException设置方法抛出了特定的异常@BeforeSuite,则会出现这种情况。

请参阅(可能是欺骗) TestNG - How to force end the entire test suite from the BeforeSuite annotation if a condition is met

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