appium自动化,失败自动截图
1、创建监听器类TestNGListener,重写onTestFailure方法,里面定义了 监听的driver ,截图文件路径和名称
package utils;
import cases.AppiumBasic;
import io.appium.java_client.AppiumDriver;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestNGListener extends TestListenerAdapter{
@Override
public void onTestFailure(ITestResult tr){
try {
super.onTestFailure(tr);
//调用屏幕截图方法
captureScreenShot(tr,tr.getMethod().getMethodName());
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public void captureScreenShot(ITestResult result,String name) {
AppiumDriver driver = AppiumBasic.getDriver();
File srcFile = driver.getScreenshotAs(OutputType.FILE);
String filepath = "E:\\appimage\\education_test";
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
try {
FileUtils.copyFile(srcFile, new File(filepath + File.separator +name+"-"+ dateFormat.format(new Date()) + ".png"));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
2、driver的来源
package cases;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeClass;
import java.net.MalformedURLException;
import java.net.URL;
public class AppiumBasic {
public static AndroidDriver driver;
@BeforeClass
public void beforeClass() throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(CapabilityType.BROWSER_NAME,"");
caps.setCapability("platformName","Android"); //测试平台
caps.setCapability("deviceName","127.0.0.1:62025"); //指定测试机的ID
caps.setCapability("appPackage","ai.avatec.android"); //被测APP包名
caps.setCapability("appActivity","ai.avatec.android.ui.main.view.MainActivity"); //被测APP入口activity
caps.setCapability("appWaitActivity","ai.avatec.android.ui.main.view.MainActivity");
caps.setCapability("noSign",true); //noSign表示不重签名,设置为true表示不重签名app
caps.setCapability(AndroidMobileCapabilityType.NO_SIGN,true);
//UNICODE_KEYBOARD表示unicode输入法,支持中文输入,支持键盘隐藏
caps.setCapability(AndroidMobileCapabilityType.UNICODE_KEYBOARD,true);
//重置输入法为设备原来的
caps.setCapability(AndroidMobileCapabilityType.RESET_KEYBOARD,true);
caps.setCapability("automationName", "UiAutomator2");
//每次启动时覆盖session,否则第二次后运行会报错不能新建session
caps.setCapability("sessionOverride",true);
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), caps);
}
public static AppiumDriver getDriver()
{
return driver;
}
}
3、配置监听器
有两种配置方法
(1)有两种配置方法在需要捕捉的类上方
(2)在testng.xml里配置监听器
两种方式的差别在于,类上方配置,只能抓获这个类报错的截图。