testng實現場景恢復

自動化測試過程當中存在不少的不穩定性,例如網絡的不穩定,瀏覽器無響應等等,這些失敗每每並非產品中的錯誤。那麼這時咱們須要對執行失敗的場景恢復從新執行,確認其是否確實失敗。 java

之前使用QTP的時候也使用了場景恢復,那麼testng的場景恢復怎麼作呢?瀏覽器

1、查看testng如今接口網絡

首先,咱們來看一下TestNG的IRetryAnalyzer接口(由於個人項目是用maven管理,因此接口位置是:Maven Dependencies-testng.jar-org.testng-IRetryAnalyzer.class)maven

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。
 
2、實現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;
    }

}

 

3、添加監聽spa

  這時咱們還要經過接用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);  
        } 
        
    }

}

 

4、配置testng監聽器code

最後,咱們只要在testng.xml裏面設置監聽就能夠了,在testng.xml中添加以下配置:orm

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

 

5、結果展現xml

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

  

  在 log輸出中,咱們能夠看到TClassManageTest中的方法inputClassList是重跑了三次的。

  

相關文章
相關標籤/搜索