如何在测试失败时使selenium测试套件失败?

时间:2014-09-22 12:52:07

标签: selenium selenium-webdriver

假设testng.xml(它是测试套件)文件包含100个测试。如果发生第一次失败,测试套件怎么会失败?

3 个答案:

答案 0 :(得分:1)

据我所知,单元测试意味着独立 - 而TestNG是单元测试框架。这就是TestNG执行所有测试用例的原因。如果您想在第一次测试失败后失败测试套件,则必须使用TestNG的另一个功能 - 测试依赖项

testNG test dependent-methods

@Test 
public void serverStartedOk() {} 

@Test(dependsOnMethods = { "serverStartedOk" }) 

public void method1() {} 

这是硬测试依赖的示例。但是,最佳做法是使您的测试方法独立。

答案 1 :(得分:0)

您还可以使用Assert.assertTrue();或False使用其他方式。 希望它有所帮助。

答案 2 :(得分:0)

由于我不会进入的原因,我建议不要在第一次失败时实施套件失败的东西。

但是,如果我要构建这样的东西,我可能会通过实现IInvokedMethodListener

的方法监听器来实现它。

有一次,我在afterInvocation()中检测到失败,然后我会立即开始强制失败beforeInvocation()中的所有后续测试。

IInvokedMethodListener的Javadocs位于 - http://testng.org/javadocs/org/testng/IInvokedMethodListener.html

示例实现可能如下所示;

public class SuiteFailingInvokedMethodListener implements IInvokedMethodListener {
    private static volatile boolean failing;

    public SuiteFailingInvokedMethodListener() {
        failing = false;
    }

    @Override
    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
        if (failing) {
            throw new RuntimeException("Test skipped due to a detected failure in the overall suite.");
        }
    }

    @Override
    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
        if (! testResult.isSuccess()) {
            failing = true;
        }

        //Update the test Result with "Skipped".  
        //Alternatively, you could use omit this code.
        //The RuntimeException thrown above will mark the test with "Failed" by default.
        if ((failing) && 
                (testResult.getThrowable().getMessage().contains("Test skipped"))) {
            testResult.setStatus(ITestResult.SKIP);
        }
    }

}

一旦有了这个监听器,你可以通过在suite.xml中添加这样的一行来将它连接到你的套件

 <listeners>
  <listener class-name="org.mycompany.listeners.SuiteFailingInvokedMethodListener" />
 </listeners>
相关问题