前言
在案例执行过程中,往往需要对失败的案例进行重跑,TestNG亦提供相应的实现方案。
示例
当套件中的测试执行失败时,TestNG都会创建一个名为testng-failed.xml的文件,该XML文件包含运行失败的方法的信息,允许您快速重现失败,而不必运行整个测试,如下所示:
编写测试类:
import org.testng.Assert;
import org.testng.annotations.*;
public class TestNGHelloWorld1 {
@BeforeTest
public void bfTest() {
System.out.println("TestNGHelloWorld1 beforTest!");
}
@Test(expectedExceptions = ArithmeticException.class, expectedExceptionsMessageRegExp = ".*zero")
public void helloWorldTest1() {
System.out.println("TestNGHelloWorld1 Test1!");
int c = 1 / 0;
Assert.assertEquals("1", "1");
}
@Test()
@Parameters(value = "para")
public void helloWorldTest2(@Optional("Tom")String str) {
Assert.assertEquals("1", "2");
System.out.println("TestNGHelloWorld1 Test2! "+ str);
}
@AfterTest
public void AfTest() {
System.out.println("TestNGHelloWorld1 AfterTest!");
}
}
执行:
D:\IntelliJ_IDEA_workspace\TestNG>java -classpath "%classpath%;D:\IntelliJ_IDEA_workspace\TestNG\lib" org.testng.TestNG -d tom testng14.xml
执行后,可发现tom目录下,生成了一个testng-failed.xml文件。
testng-failed.xml
testng-failed.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite guice-stage="DEVELOPMENT" name="Failed suite [All Test Suite]">
<test name="Test(failed)">
<parameter name="para" value="Tomandy"/>
<classes>
<class name="TestNGHelloWorld1">
<methods>
<include name="helloWorldTest2" invocation-numbers="0"/>
<include name="AfTest"/>
<include name="bfTest"/>
</methods>
</class> <!-- TestNGHelloWorld1 -->
</classes>
</test> <!-- Test(failed) -->
</suite> <!-- Failed suite [All Test Suite] -->
后续需要重跑失败案例,只需执行testng-failed.xml即可。但是在持续集成实施过程中,我们更希望的是用例执行失败后自动重跑,可通过TestNG提供的retryAnalyzer实现,示例如下:
实现IRetryAnalyzer。
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class MyRetry implements IRetryAnalyzer {
private int retryCount = 0;
private static final int maxRetryCount = 3;
public boolean retry(ITestResult iTestResult) {
if (retryCount < maxRetryCount) {
retryCount++;
return true;
}
return false;
}
}
helloWorldTest2方法添加retryAnalyzer:
import org.testng.Assert;
import org.testng.annotations.*;
public class TestNGHelloWorld1 {
@BeforeTest
public void bfTest() {
System.out.println("TestNGHelloWorld1 beforTest!");
}
@Test(expectedExceptions = ArithmeticException.class, expectedExceptionsMessageRegExp = ".*zero")
public void helloWorldTest1() {
System.out.println("TestNGHelloWorld1 Test1!");
int c = 1 / 0;
Assert.assertEquals("1", "1");
}
@Test(retryAnalyzer = MyRetry.class) //失败重跑
@Parameters(value = "para")
public void helloWorldTest2(@Optional("Tom")String str) {
Assert.assertEquals("1", "2");
System.out.println("TestNGHelloWorld1 Test2! "+ str);
}
@AfterTest
public void AfTest() {
System.out.println("TestNGHelloWorld1 AfterTest!");
}
}
执行后,可发现helloWorldTest2方法重跑了3遍。
retry
网友评论