TestNGとAppiumによるテスト実行失敗時の自動スクリーンショット機能

スクリーンショットを取得するためのリスナークラス「ScreenShotListener」を作成し、onTestFailureメソッドをオーバーライドします。このメソッド内では、監視対象のドライバー、スクリーンショット保存先パスおよびファイル名を定義します。

package com.fsssc.htsgl.utils;
import io.appium.java_client.android.AndroidDriver;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import com.fc.boxapk.ApkBoxOperation;

public class ScreenShotListener extends TestListenerAdapter {
    @Override
    public void onTestFailure(ITestResult tr) {
         // Androidアプリケーション操作クラス
        ApkBoxOperation apkRemoteControl = ApkBoxOperation.getInstance();
        // スクリーンショットを取得するドライバー
        AndroidDriver<WebElement> driver = apkRemoteControl.driver;
        // スクリーンショットフォルダ
        File path = new File("screenshots");
        // スクリーンショットの保存場所とファイル名(形式:識別子_クラス名.メソッド名.png)
        String name = path.getAbsolutePath() + File.separator + MysqlUtils.executionFlag+"_"+MysqlUtils.exeClassName +"."+ tr.getMethod().getMethodName() + ".png";
        // 
        File screenShot = driver.getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenShot, new File(name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

テストケースの実装

package com.fsssc.htsgl.testcases;
import java.io.IOException;
import junit.framework.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import com.fc.boxapk.ApkBoxOperation;
import com.fc.htgl.utils.MysqlUtils;
import com.fc.htgl.utils.PropsUtil;
import com.fc.htgl.utils.ScreenshotListener;
// リスナー設定
@Listeners({ScreenShotListener.class})
public class DevTest{
    // Androidアプリケーション初期化
    ApkBoxOperation apkBoxOperation  = ApkBoxOperation.getInstance();  
    // 実行識別子にタイムスタンプを設定
    String executionFlag = PropsUtil.timeToString();
    
    @Test
    public void testCase() throws IOException {
         // 現在のクラス名を変数に格納
        MysqlUtils.exeClassName = Thread.currentThread().getStackTrace()[1].getClassName();
        // 実行識別子を変数に格納
        MysqlUtils.executionFlag = executionFlag;
        // Androidアプリケーションログイン
        apkBoxOperation.courierLogin("13488883323", "4566656");    
        // テスト終了時にアサーションエラーを発生させ、スクリーンショットを撮影
        Assert.assertFalse(true);
        // アプリケーションを閉じる
        apkBoxOperation.driver.closeApp();        
    }
}

スクリーンショットファイル名の例:

20161101151840_com.fsssc.htsgl.testcases.DevTest.testCase.png

タグ: TestNG appium Android スクリーンショット 自動テスト

7月2日 23:10 投稿