我正在尝试在我的测试套件中构建逻辑,这样如果测试失败,它会自动重新运行。当我的测试失败时,它会按预期重新运行,但我的测试套件包含一个@AfterMethod,当测试重新运行时,它似乎被忽略了。
我按照这里给出的解决方案:
https://www.softwaretestingmaterial.com/run-failed-test-cases-using-testng/
所以我创建了2个类:
package softwareTestingMaterial;
import org.testng.IRetryAnalyzer; import org.testng.ITestResult;
public class RetryFailedTestCases implements IRetryAnalyzer {
private int retryCnt = 0;
private int maxRetryCnt = 2;
public boolean retry(ITestResult result) {
if (retryCnt < maxRetryCnt) {
System.out.println("Retrying " + result.getName() + " again and the count is " + (retryCnt+1));
retryCnt++;
return true;
}
return false;
}
}
和
package softwareTestingMaterial;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;
public class RetryListenerClass implements IAnnotationTransformer {
@Override
public void transform(ITestAnnotation testannotation, Class testClass, Constructor testConstructor, Method testMethod) {
IRetryAnalyzer retry = testannotation.getRetryAnalyzer();
if (retry == null) {
testannotation.setRetryAnalyzer(RetryFailedTestCases.class);
}
}
}
我用于执行测试的XML文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Test Suite 1">
<listeners>
<listener class-name="org.testng.reporters.EmailableReporter2" />
<listener class-name="CustomUtils.RetryListenerClass" />
</listeners>
<test name="Test 1">
<classes>
<class name="WebTests.CheckoutTestWeb"/>
</classes>
</test>
</suite>
当@Test抛出异常时,@ AfterMethod可能无法运行。要确保执行@AfterMethod,请添加看起来像@AfterMethod(alwaysRun = true)的alwaysRun属性