Appium 使用 Appium Android 自动化测试,失败时自动截图

小星 · 2017年06月20日 · 最后由 dd 回复于 2018年04月11日 · 1357 次阅读
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>

截图的路径可以在控制台的输出中看到

共收到 6 条回复 时间 点赞

刚好需要,顺手拿走!😏

白纸 回复

哈哈哈希望能帮到你

小星 回复

class implements IHookable
@Listeners({class.class})

这种方式的 testng 实现截图试过吗

白纸 回复

这个倒没有试过
不过,可能是这样子写吧

@Listeners(.class)
public class listenerTest {

    @Test
    public void test1(){

    }

    @Test
    public void test2(){

    }
}

你好!请问一下 import osvc.mobile.tests.PhoneBaseClass;这个类怎么导入?还有如果没有这个类的话,File srcFile = PhoneBaseClass.getDriver().getScreenshotAs(OutputType.FILE);这里的 PhoneBaseClass 会报错

File srcFile = PhoneBaseClass.getDriver().getScreenshotAs(OutputType.FILE);是不是改为 File srcFile = driver.getScreenshotAs(OutputType.FILE);?

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册