【问题标题】:How to stop TestNG from running after a test fail测试失败后如何阻止TestNG运行
【发布时间】:2019-10-06 19:29:16
【问题描述】:

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

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

如何解决?

【问题讨论】:

  • 如果一个测试失败,为什么要取消整个套件的运行?
  • 这意味着一个显示停止器,如果此测试失败,则继续运行测试套件的其余部分没有意义。
  • 但是你的其他测试不也很重要吗?如果您的其他测试之一也发现了一个显示停止器怎么办?如果你在第一个之后停下来,你只会发现一个而不是所有的问题。
  • 这正是我需要做的:如果此特定测试失败,则停止运行测试。

标签: java selenium testng


【解决方案1】:

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

后来,在下一个测试中,我在 @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;
    }
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      见(可能是骗人的) TestNG - How to force end the entire test suite from the BeforeSuite annotation if a condition is met

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

      【讨论】:

        【解决方案4】:

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

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

        JavaDoc of the dependsOnMethods parameter:

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

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

        【讨论】:

        • 如果类中有十几个方法怎么办?
        • 遗憾的是,如果这些方法在同一个测试类中,则必须将其添加到每个测试方法中。这也可以在类级别上设置,但我不确定,如果这真的被 TestNG 支持。文档中的示例仅在方法级别使用它。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-28
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多