package osvc.util;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import osvc.mobile.tests.PhoneBaseClass;
public class ScreenshotListener implements ITestListener{
AppiumDriver<MobileElement> driver;
public void onTestStart(ITestResult result) {}
public void onTestSuccess(ITestResult result) {}
public void onTestFailure(ITestResult result) {
System.out.println("========================failed, create snapshot here==============");
captureScreenShot(result);
}
public void onTestSkipped(ITestResult result) {}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {}
public void onStart(ITestContext context) {}
public void onFinish(ITestContext context) {}
public void captureScreenShot(ITestResult result){
File srcFile = PhoneBaseClass.getDriver().getScreenshotAs(OutputType.FILE);
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
File location = new File("screenshots");
String dest = result.getMethod().getRealClass().getSimpleName()+"."+result.getMethod().getMethodName();
File targetFile = new File(location.getAbsolutePath()+File.separator+dest+dateFormat.format(new Date())+".png");
System.out.println("----------------- file is " + targetFile.getPath());
try {
FileUtils.copyFile(srcFile, targetFile);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
然后在 testng.xml 中调用即可
<suite name="" verbose="">
<listeners>
<listener class-name="osvc.util.ScreenshotListener" />
</listeners>
<test>
..........
</test>
</suite>
截图的路径可以在控制台的输出中看到