Appium监听,失败自动截图——2018-04-17

自动化跑用例,必须要有结果展示,才能知道脚本跑测的情况,而我使用的是Appium+TestNG+java来写脚本,而截图尤为重要,脚本pass倒没事,若是fail,那怎么办?所以,我们需要一个脚本跑fail了就自动截图的功能。那么问题来了,这个组合,默认情况下,并没有截图功能,那么我们就需要自己写一个截图的功能。
经过查找资料,了解到,TestNG作为测试框架,有多个监听器接口和类,这里我们需要用到的是ITestListener接口,只需要注册就可以监听脚本,

如何实现监听器类?

其方法有如下

onFinish(ITestContext arg0)

onStart(ITestContext arg0)

onTestFailedButWithinSuccessPercentage(ITestResult arg0)

onTestFailure(ITestResult result)

onTestSkipped(ITestResult arg0)

onTestStart(ITestResult arg0)

onTestSuccess(ITestResult arg0)

词即义,方法什么意思看词语就知道,此处,我们需要的是用例失败即自动截图功能,那我们把截图功能放到onTestFailure(ITestResult result)方法下,那么我们需要先建一个类,我们就叫它ScreenshotListener吧,然后把这个类实现ITestListener接口,即

public class ScreenshotListener implements ITestListener

onTestFailure方法代码如下

    public void onTestFailure(ITestResult result)
    {

        // 跑fail则截图
        // 获取屏幕截图
        File srcFile = (driver).getScreenshotAs(OutputType.FILE);
        // System.out.println(srcFile.getAbsolutePath().toString());
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_hhmmss");
        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("截图位置:");
        System.out.println("----------------- file is " + targetFile.getPath());
        try
        {
            FileUtils.copyFile(srcFile, targetFile);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        
    }

怎么用监听器?

此处,我只实现了用例失败自动监听截图监听器类,那么怎么用呢?我用的方法是在脚本类前面加入一个注解,代码如下

import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidKeyCode;
@Listeners({ScreenshotListener.class})  //此处需要写入监听器注解
public class Display
{
     private AndroidDriver driver;
    
    AppiumUtil appiumUtil = new AppiumUtil();
    
    /**
     * 1.屏幕上方跳出亮度条调节框
     * 2.亮度条调节框消失
     */
  @Test
    public void brightnessLevel_003()
    {
                driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        WebElement webElement = driver.findElementByAndroidUIAutomator(appiumUtil.scrollTo("Display", AppiumUtil.NAME));
        webElement.click();
        
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        webElement = driver.findElementByName("Brightness level");
        
        webElement.click();
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        driver.pressKeyCode(AndroidKeyCode.BACK);
    }

    /** 
     * step
    1.点击进入设置 --> 显示 --> 壁纸,观察界面
    
    result
    1.界面显示动态壁纸、壁纸、谷歌相册
    */
    @Test
    public void enterWallpaper_012()
    {
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        WebElement webElement = driver.findElementByName("Wallpaper");
        webElement.click();
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
    }
    @BeforeTest
    public void beforeTest()
        throws Exception
    {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("deviceName", "Android Devices");
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("platformVersion", "7.0");
        capabilities.setCapability("udid", "HKL3XDH8");
        capabilities.setCapability("automationName", "Uiautomator2");
        capabilities.setCapability("appPackage", "com.android.settings");
        capabilities.setCapability("appActivity", ".Settings");
        capabilities.setCapability("NoReset", true);
        driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
        ScreenshotListener.driver = driver;  //此处需要把driver传入给监听器,否则监听器使用driver的时候,会抛空指针
        System.out.println("启动应用!");
    }
    
    @AfterTest
    public void afterTest()
    {
        driver.quit();
        System.out.println("退出driver!");
    }
}

然后试跑一下,我刻意把用例跑失败,得出如下,图片好像上传不了,稍后传上
总结,自动化跑脚本失败时,可以通过添加监听器类,实现自动截图功能,监听器类的实现方法和如何使用监听器类以上有提到。
疑问:注册监听器的另外一种方式,也可以在testng.xml文件添加监听器,我的如下

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false">


  <listeners>
    <listener class-name="com.hq.prodreamer.DisplayTest.ScreenshotListener" />
  </listeners> 

  <test name="Display">
    <classes>
      <class name="com.hq.prodreamer.DisplayTest.Display"/>
    </classes>
    
    <listeners>
        //这是你需要加的东西
        <listener class-name="org.uncommons.reportng.HTMLReporter" />
        <listener class-name="org.uncommons.reportng.JUnitXMLReporter" />
    </listeners>
    
  </test> <!-- Test -->
</suite> <!-- Suite -->

不知为何,我在testng.xml注册监听器,也没有监听成功?而需要在脚本类前面添加监听器注释?有懂的大神可以指导一下。

接上。
终于知道为何在testng.xml注册监听器没有监听成功了,上面的com.hq.prodreamer.DisplayTest.ScreenshotListener监听器没有写进<test>...</test>里面,故没有监听到Display类的情况,所以我们要把监听器同样像reportng一样写进去,代码如下

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false">
    <test name="Display">
        <classes>
            <class name="com.hq.prodreamer.DisplayTest.Display"/>
        </classes>
    
        <listeners>
        //这是你需要加的东西
            <listener class-name="org.uncommons.reportng.HTMLReporter" />
            <listener class-name="org.uncommons.reportng.JUnitXMLReporter" />
            <listener class-name="com.hq.prodreamer.DisplayTest.ScreenshotListener" />
        </listeners>
    </test> <!-- Test -->
</suite> <!-- Suite -->

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 感谢原作者的奉献,原作者博客地址:http://blog.csdn.net/zhu_ai_xin_520/arti...
    狼孩阅读 14,130评论 1 35
  • 基于 SELENIUM 的自动化测试架构 非常感谢各位查阅本篇文章,笔者在此感谢各位。 目前市面上有分门别类的自动...
    厲铆兄阅读 6,114评论 6 43
  • 梦如易碎的明月光, 人是月下孤魂野鬼。 偶尔闻一窖酒香, 醉在星辉斑斓里; 或是枕卧一树桃花, 一颗心轻轻、轻轻地...
    陌九阅读 190评论 0 3
  • 记忆中家乡的葬礼上总会放一种特制的土炮,又响又亮。村里每逢葬礼总会出现那样一对夫妇,女人弱智,男人便是人口中的缺心...
    傻傻小二妞阅读 292评论 0 1
  • 时间已是黄昏,我来到了这家小网吧里开始了兼职工作,当夜班网管。 刚进来后不久黄总就跟着进来了,今天的他看起来整个打...
    许你故作姿态阅读 1,218评论 1 6