appium安卓自动化的 常用driver方法封装

做安卓自动化的时候,很多方法写起来会造成代码冗余,把这部分封装起来 ,添加到androidUI工具类里,随时可调用

都放在这个类下面:

@Component
public class AndroidUI{

首先要进行driver实例的连接,连接后才能做相应的一些操作,及得造作完成要关闭driver,避免内存占用

连接driver

/*
* @method: 连接driver
*/
public void setUp(DesiredCapabilities dCapabilities) throws MalformedURLException {
driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), dCapabilities);
logger.info(driver.currentActivity());
}

断开driver

/*
* @method: 断开driver
*/
public void tearDown() throws Exception {
if (null != driver) {
driver.quit();
}
}

休眠方法时间定义毫秒或秒都行吧,看个人喜好,我这里为了写着定义成秒的,系统自带是毫秒

/*
* @method: 休眠方法
* @param: int seconds 休眠的时间,单位为s(必须大于等于1)
* @other: Appium类内设置的所有操作方法均会在正常结束后休眠1s,无需在用例中手动休眠
*/
public void sleep(int time) {
if (!((time >= 1) && (time % 1 == 0))){
Assert.fail("sleep: Parameter ERROR!");
}
try {
Thread.sleep(time * 1000);
//System.out.println("休息");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

上面休眠方法是死的,而元素加载时间不确定的,可以用下面等待找到元素的灵活等待时间

/*
* @method: 比sleep更有客观的延迟方法,在一定时间内等待某元素在屏幕中出现。
* @param: String target 等待的目标
* int time 等待时间,单位为ms,必须是1的正整数倍
* @other: Appium类内设置的所有操作方法均会在正常结束后休眠1s,无需在用例中手动休眠
*/
public boolean waitFor(String target,int time) { try {
if (!((time >= 1) && (time % 1 == 0))){
Assert.fail("waitFor: Parameter ERROR!");
}
String result = null;
String page = driver.getPageSource();
logger.info("Waiting for " + target + " ..."); for (int i = 1; i <= time; i++) {
if (page.contains(target)) {
result = "Succeeded.";
logger.info(result);
break;
} else {
sleep(1);
page = driver.getPageSource();
}
}
} catch (Exception e) {
logger.error("元素:"+target+"不存在");
sleep(1);
e.printStackTrace();
return false;
}
return true;
} 然后是滑动操作,这个操作是比较常用的手势,按照方向做了封装,调用时把方向作为参数使用
/*
* @method: 滑动操作
* @param: String direction, right 向右四分之一/left 向左四分之一/up 向上四分之一/down 向下四分之一/top 到顶/end 到底
*/
public void swipeTo(String direction) { int width=driver.manage().window().getSize().width;
int height=driver.manage().window().getSize().height; if (direction == "right") {
driver.swipe(width/4, height/2, width*3/4,height/2, 500);
logger.info("右滑");
} else if (direction == "left") {
driver.swipe(width*3/4, height/2, width/4, height/2, 500);
logger.info("左滑");
} else if (direction == "down") {
driver.swipe(width/2, height/4, width/2, height*3/4, 500);
logger.info("下滑");
} else if (direction == "up") {
driver.swipe(width/2, height*3/4, width/2, height/4, 500);
logger.info("上滑");
} else if (direction == "end") {
String page1;
String page2;
do {
page1 = driver.getPageSource();
driver.swipe(width/2, height*3/4, width/2, height/4, 500);
sleep(2);
page2 = driver.getPageSource();
} while (!page1.equals(page2));
logger.info("滑到底");
} else if (direction == "top") {
String page1;
String page2;
do {
page1 = driver.getPageSource();
driver.swipe(width/2, height/4, width/2, height*3/4, 500);
sleep(4);
page2 = driver.getPageSource();
} while (!page1.equals(page2));
logger.info("滑到顶");
}
sleep(1);
} 学过安卓开发的都知道,layout中有各种view、包括textView、imageView、Button、checkBox、radioButton、alertDialog、processDialog啥的
所以对于这些的点击处理最好是根据id或text作为参数封装方法来进行定位点击操作
例如:
/*
* @method: 通过想点击文字的控件id和顺序index点击文字,当第一屏未找到文字会向下滚动查找,若滚到底扔未发现文字断言失败;方法结束后休眠1s
* @param: String id 想点击文字的id
* int index 顺序
*/
public void clickTextById(String id, int index) { String page1;
String page2;
int result = 0; do {
page1 = driver.getPageSource();
if (page1.contains(id)) {
if (index == 0) {
AndroidElement imageElement = driver.findElementByXPath("//android.widget.TextView[contains(@resource-id,'" + id + "')]");
logger.info("Text " + id + " found.");
imageElement.click();
logger.info("Text " + id + " clicked.");
result = 1;
} else if (index > 0) {
List<AndroidElement> imageElements = driver.findElementsByXPath("//android.widget.TextView[contains(@resource-id,'" + id + "')]");
AndroidElement imageElement = imageElements.get(index);
logger.info("Text " + id + " found.");
imageElement.click();
logger.info("Text " + id + " clicked.");
result = 1;
}
break;
} else {
this.swipeTo("down");
page2 = driver.getPageSource();
}
} while (!page1.equals(page2)); if (result == 0) {
Assert.fail("Clicking Text " + id + " failed.");
}
sleep(1);
}

当然,我们进行测试,是为了确定页面中有某元素或是没有某元素,所以用的最多的方法是search

public void search(String list) {

   String pageSource = this.pageSource();
if (!list.contains(",")) {
if (pageSource.contains(list)) {
logger.info(list + " is found.");
} else {
takeScreenShot("FAILURE(search)_" + list);
Assert.fail("Searching " + list + " failed.");
}
} else {
String elements[] = list.split(",");
for (int i = 0; i <= ((elements.length)-1); i++) {
if (elements[i].contains(" ")) {
elements[i] = elements[i].trim();
}
if (pageSource.contains(elements[i])) {
logger.info(elements[i] + " is found.");
} else {
takeScreenShot("FAILURE(search)_" + list);
Assert.fail("Searching " + elements[i] + " failed.");
}
}
}
sleep(1);
} 上面要说明一下。
takeScreenShot("FAILURE(search)_" + list); 这个是单独写的截屏函数,
这个方法在出现错误时,保存个截图到某一文件夹下更好,这样可以方便定位问题
public void takeScreenShot(String methodName) {
File srcFile = AndroidUI.driver.getScreenshotAs(OutputType.FILE);
//利用FileUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。
// FileUtils.copyFile(srcFile, new File("screenshot.png"));
String fileName = methodName + "_" + DateUtil.formatNowTime(12) + ".png";
String filePath = "C:\\Users\\linyuchen\\Pictures\\AndroidUI";
try {
FileUtils.copyFile(srcFile, new File(filePath+"\\"+fileName));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println("taking ScreenShots"); } 其实还有很多很多方法 ,大家可以根据自己喜好来定义 都可以随意些
												

appium安卓自动化的 常用driver方法封装的更多相关文章

  1. appium安卓自动化常见问题处理

    appium安卓自动化常见问题处理 1.seesionnotcreatedexception 遇到这个首先确定下jdk需要1.7以上 然后还要确定appium是启动状态,可以cmd重启下appium ...

  2. 常用js方法封装

    常用js方法封装 var myJs = { /* * 格式化日期 * @param dt 日期对象 * @returns {string} 返回值是格式化的字符串日期 */ getDates: fun ...

  3. JS常用公共方法封装

    _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||/ ...

  4. JavaScript常用工具方法封装

    因为工作中经常用到这些方法,所有便把这些方法进行了总结. JavaScript 1. type 类型判断 isString (o) { //是否字符串 return Object.prototype. ...

  5. Selenium3+python自动化007-Selenium常用定位方法

    自动化测试只要掌握四步操作:获取元素,操作元素,获取返回结果,断言(返回结果与期望结果是否一致),最后自动出测试报告.元素定位在这四个环节中是至关重要的,如果说按学习精力分配的话,元素定位占70%:操 ...

  6. 项目常用JS方法封装--奋斗的IT青年(微信公众号)

                                                                                                        ...

  7. Socket一些常用的方法封装

    public class SocketHelper { /// <summary> /// 功能描述:得到一个实例对象 /// </summary> /// <retur ...

  8. 常用js方法封装使用

    // 冒泡排序 export function bubbleSort(arr) { let i = arr.length - 1; while (i > 0) { let maxIndex = ...

  9. appium+python自动化24-滑动方法封装(swipe)

    swipe介绍 1.查看源码语法,起点和终点四个坐标参数,duration是滑动屏幕持续的时间,时间越短速度越快.默认为None可不填,一般设置500-1000毫秒比较合适. swipe(self, ...

随机推荐

  1. 启动mysql出现1067错误

    0. 打开mysql\bin\my.ini,查找[mysqld],在[mysqld]下面添加一行文字,skip-grant-tables 即组成 [mysqld] skip-grant-tables[ ...

  2. 使用 Scrapy 构建一个网络爬虫

    来自weixin 记得n年前项目需要一个灵活的爬虫工具,就组织了一个小团队用Java实现了一个爬虫框架,可以根据目标网站的结构.地址和需要的内容,做简单的配置开发,即可实现特定网站的爬虫功能.因为要考 ...

  3. 【Oracle】事务处理

    名词解释 DML:Data Manipulation Language (数据库操纵语言) 例如:DELETE.INSERT.UPDATE.SELECT DDL:Data Definition Lan ...

  4. 前端开发不容错过的jQuery图片滑块插件(转)

    作为前端开发者,我们会碰到很到各种各样的jQuery插件.今天要分享的几款jQuery图片滑块插件,也就是jQuery焦点图插件,基本上会在每个网站都有应用,可以下载看看,也许你可以用到. 1.jQu ...

  5. Linux密钥认证错误解决

    问题描述: Xshell用key认证登录,提示所选的用户密钥未在远程主机上注册 问题解决: 查看日志/var/log/secure,基本上都是用户根目录的权限问题 根据日志提示: Authentica ...

  6. 在Eclipse中开发C/C++项目

    摘要:通过本文你将获得如何在Eclipse平台上开发C/C++项目的总体认识.虽然Eclipse主要被用来开发Java项目,但它的框架使得它很容易实现对其他开发语言的支持.在这篇文章里,你将学会如何使 ...

  7. VS:"64位调试操作花费的时间比预期要长"的一解决途径

    解决办法之一: 在命令提示符那里打入如下命令: netsh winsock reset catalognetsh int ip reset reset.log hit 重启电脑后,即可

  8. iOS获取本地沙盒视频封面图片(含swift实现)

    最近做了个小应用,有涉及到本地视频播放及列表显示. 其中一个知识点就是获取本地存储视频,用来界面中的封面显示. 记录如下: //videoURL:本地视频路径 time:用来控制视频播放的时间点图片截 ...

  9. SQLAlchemy基本使用(Flask中)

    SQLAlchemy介绍 SQLAlchemy是一个基于Python实现的ORM框架. 该框架建立在 DB API之上,使用关系对象映射进行数据库操作,简言之便是:将类和对象转换成SQL,然后使用数据 ...

  10. HDUOJ ------1398

    http://acm.hdu.edu.cn/showproblem.php?pid=1398 Square Coins Time Limit: 2000/1000 MS (Java/Others)   ...