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

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

一个TestNG类可以有不同的测试,比如test1、test2、test3等。在运行测试套件时可能会出现一些失败,用户可能会在@Test方法之间出现失败。一旦一个测试方法失败,它就会跳过@Test方法的剩余代码并转到下一个@Test方法。然而,用户可能希望在获得第一个失败后跳过剩余的所有@Test方法。

针对这样的使用场景,有两种最流行的解决方案:

  • 编写 dependsOnMethods 注解 – 但这个解决方案只适用于用户知道确切的依赖方法,否则在大型套件中会非常混乱。

  • 使用 IInvokedMethodListener 来添加一个在整个套件中通用的逻辑。

在这篇文章中,让我们分析如何使用 IInvokedMethodListener 在第一个失败后停止套件执行。

步骤

  • 步骤1:导入 org.testng.annotations.Test 用于 TestNG。

  • 步骤2:在 NewTest 类中编写 @test 注解。

  • 步骤3:为 @Test 注解创建一个方法,如 test1。

  • 步骤4:重复上述步骤来创建 test2 和 test3。在 test2 中添加一个失败断言。

  • 步骤5:现在,创建一个 ListenerClass,使用 IInvokedMethodListener 来检查前一个 @Test 方法的状态。如果它得到失败状态,忽略剩余的套件。

  • 步骤6:现在创建 testNG.xml 并添加 Listener 类。

  • 步骤7:现在,在IDE中运行 testNG.xml 或直接运行 testNG 类,或者使用命令行编译和运行。

示例

以下代码创建了一个 TestNG 类,并显示了 Listener 的功能:

src/NewTest.java

import org.testng.annotations.Test;
public class NewTest {
    @Test()
    public void testCase1() {
        System.out.println("in test case 1 of NewTest");
    }
    @Test()
    public void testCase2() {
        System.out.println("in test case 2 of NewTest");
      assert false;
    }
    @Test()
    public void testCase3() {
        System.out.println("in test case 3 of NewTest");

    }
}

src/ListenerClass.java

import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
import org.testng.SkipException;

public class ListenerClass implements IInvokedMethodListener {

    private boolean hasFailures = false;

    @Override
    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
        synchronized (this) {
            if (hasFailures) {
                throw new SkipException("Skipping this test");
            }
        }
    }

    @Override
    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
        if (method.isTestMethod() && !testResult.isSuccess()) {
            synchronized (this) {
                hasFailures = true;
            }
        }
    }
}

testng.xml

这是一个用来组织和运行TestNG测试用例的配置文件。

当只需要执行部分测试而不是全部套件时,它非常方便。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Parent_Suite">
    <listeners>
        <listener class-name="ListenerClass"/>
    </listeners>
    <test name="group test">
        <classes>
            <class name="NewTest" />
        </classes>
    </test>
</suite>

输出

[INFO] Running TestSuite
in test case 1 of NewTest
in test case 2 of NewTest
[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 1, Time elapsed: 0.671 s <<< FAILURE! - in TestSuite
[ERROR] NewTest.testCase2  Time elapsed: 0.009 s  <<< FAILURE!
java.lang.AssertionError
    at NewTest.testCase2(newTest.java:14)
[INFO] 
[INFO] Results:
[INFO] 
[ERROR] Failures: 
[ERROR]   NewTest.testCase2:14
[INFO] 
[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 1

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程

TestNG 精选笔记