执行testng appium用例失败,自动截图
新建一个截图监听类ScreenShotListener ,重写onTestFailure方法,里面定义了 监听的driver ,截图文件路径和名称
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) { //安卓程序的操作类 ApkBoxOperation apkRemoteControl = ApkBoxOperation.getInstance(); //监控截图的driver AndroidDriver<WebElement> driver = apkRemoteControl.driver; // 截图文件夹 File path = new File("screenshots"); //截图位置及文件名 名称为 标识 + 类名 + 方法名 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{ //安卓程序初始化 ApkBoxOperation apkBoxOperation = ApkBoxOperation.getInstance(); // 赋值一个执行编码给执行标识 String executionFlag = PropsUtil.timeToString(); @Test public void testCase() throws IOException { //本次类名赋值给变量 MysqlUtils.exeClassName = Thread.currentThread().getStackTrace()[1].getClassName(); // 执行标识赋值给变量 MysqlUtils.executionFlag = executionFlag; // 安卓程序登录 apkBoxOperation.courierLogin("13488883323", "4566656"); // 执行完毕 断言失败,执行截图 Assert.assertFalse(true); // 关掉app apkBoxOperation.driver.closeApp(); } }
执行后截图文件名:
20161101151840_com.fsssc.htsgl.testcases.DevTest.testCase.png