testng實現場景恢復


自動化測試過程中存在很多的不穩定性,例如網絡的不穩定,瀏覽器無響應等等,這些失敗往往並不是產品中的錯誤。那么這時我們需要對執行失敗的場景恢復重新執行,確認其是否確實失敗。 

以前使用QTP的時候也使用了場景恢復,那么testng的場景恢復怎么做呢?

一、查看testng現在接口

首先,我們來看一下TestNG的IRetryAnalyzer接口(因為我的項目是用maven管理,所以接口位置是:Maven Dependencies-testng.jar-org.testng-IRetryAnalyzer.class)

package org.testng;

/**
 * Interface to implement to be able to have a chance to retry a failed test.
 *
 * @author tocman@gmail.com (Jeremie Lenfant-Engelmann)
 *
 */
public interface IRetryAnalyzer {

  /**
   * Returns true if the test method has to be retried, false otherwise.
   *
   * @param result The result of the test method that just ran.
   * @return true if the test method has to be retried, false otherwise.
   */
  public boolean retry(ITestResult result);
}
這個接口只有一個方法:
  public boolean retry(ITestResult result);
  一旦測試方法失敗,就會調用此方法。如果您想重新執行失敗的測試用例,那么就讓此方法返回true,如果不想重新執行測試用例,則返回false。
 
二、實現testng失敗重跑的接口IRetryAnalyzer

   添加類TestngRetry,實現如下:

/**
 * @author Helen 
 * @date 2018年5月19日  
 */
package common;

import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
import org.testng.Reporter;

/**
 * 描述:重寫testngRetry接口,設置場景恢復
 */
public class TestngRetry implements IRetryAnalyzer {
    private int retryCount = 1;
    private static int maxRetryCount = 3;// 最大重新執行場景的次數

    /*
     * 場景恢復設置,重新執行失敗用例的次數
     */
    public boolean retry(ITestResult result) {
        if (retryCount <= maxRetryCount) {
            String message = "Retry for [" + result.getName() + "] on class [" + result.getTestClass().getName()
                    + "] Retry " + retryCount + " times";
            Reporter.setCurrentTestResult(result);
            Reporter.log(message);//報告中輸出日志
            retryCount++;
            return true;
        }
        return false;
    }

}

 

三、添加監聽

  這時我們還要通過接用IAnnotationTransformer來實現監聽,添加類TestngRetryListener,代碼如下:

/**
 * @author Helen 
 * @date 2018年5月19日  
 */
package common;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;

/**
 * 描述:實現IAnnotationTransformer接口,設置監聽
 */
public class TestngRetryListener implements IAnnotationTransformer{

    public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
        IRetryAnalyzer retry = annotation.getRetryAnalyzer();  
        if (retry == null) {  
            annotation.setRetryAnalyzer(TestngRetry.class);  
        } 
        
    }

}

 

四、配置testng監聽器

最后,我們只要在testng.xml里面設置監聽就可以了,在testng.xml中添加如下配置:

    <listeners>
        <!-- 添加場景恢復的監聽器 -->
        <listener class-name="common.TestngRetryListener"></listener>
    </listeners>

 

五、結果展示

  執行完結果后,查看測試報告,測試是有失敗的。

  

  在 log輸出中,我們可以看到TClassManageTest中的方法inputClassList是重跑了三次的。

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM