我们使用TestNG来作为自动化测试框架的基础。在运行一批testcase之后呢,我们希望能够自动Retryfailed的testcase。TestNG提供了一个IRetryAnalyzer的接口,在@Testannotation里面可以指定使用Retry类来执行retry的功能。@Test(retryAnalyzer=TestRetryAnalyzer.class
TestRetryAnalyzer类实现了IRetryAnalyzer接口。
实现逻辑为:在retry方法里,判断Retry次数是否已经超过指定的最大retry次数。如果没有返回true,否则返回false。
_______________________________________________________________________________importorg.testng.IRetryAnalyzer;importorg.testng.ITestResult;
publicclassTestRetryAnalyzerimplementsIRetryAnalyzer{privatestaticfinalStringTEST_RETRY_COUNT="testRetryCount";privateintcount=1;privateintmaxCount=1;publicTestRetryAnalyzer({StringretryMaxCount=System.getProperty(TEST_RETRY_COUNT;if(retryMaxCount!=null{maxCount=Integer.parseInt(retryMaxCount;}}publicintgetCount({returnthis.count;}publicintgetMaxCount({returnthis.maxCount;}publicsynchronizedbooleanretry(ITestResultresult{StringtestClassName=String.format("%s.%s",result.getMethod(.getRealClass(.toString(,result.getMethod(.getMethodName(;if(count<=maxCount{result.setAttribute("RETRY",newInteger(count;Logging.log("[RETRYING]"+testClassName+"FAILED,"+"Retrying"+count+"time",true;count+=1;returntrue;
}returnfalse;}}
_______________________________________________________________________________
然后,我们需要定义一个TestNGListener,来处理TestCaseRetry的状态。在onTestFailure方法里,未达到最大retry次数的失败Case,我们把它的状态设置为SKIP,这样TestNG不会把它统计为Failed的testcase。
在OnFinish方法里面处理最后TestCase的Result。>>>>
publicclassRetryTestListenerextendsTestListenerAdapter{
publicsynchronizedvoid>>>>onTestFailure(ITestResultarg0{
publicvoidonFinish(finalITestContextarg0{
if(isRetryHandleNeeded
}
{{}
skippedCases=arg0.getSkippedTests(;failedCases=arg0.getFailedTests(;
removeIncorrectlySkippedTests(arg0,failedCases;removeFailedTestsInTestNG(arg0;
}