51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 1571|回复: 4
打印 上一主题 下一主题

Appium自动化测试框架

[复制链接]

该用户从未签到

跳转到指定楼层
1#
发表于 2018-3-14 14:32:44 | 只看该作者 回帖奖励 |正序浏览 |阅读模式

1.在utils包中创建一个AppiumUtil类,这个类是对appium api进行封装的。

代码如下:

  1. 1 package utils;
  2.   2
  3.   3 import java.net.MalformedURLException;
  4.   4 import java.net.URL;
  5.   5 import java.util.List;
  6.   6 import java.util.Set;
  7.   7 import java.util.concurrent.TimeUnit;
  8.   8
  9.   9 import org.apache.log4j.Logger;
  10. 10 import org.openqa.selenium.By;
  11. 11 import org.openqa.selenium.JavascriptExecutor;
  12. 12 import org.openqa.selenium.NoSuchElementException;
  13. 13 import org.openqa.selenium.TimeoutException;
  14. 14 import org.openqa.selenium.WebDriver;
  15. 15 import org.openqa.selenium.WebElement;
  16. 16 import org.openqa.selenium.remote.DesiredCapabilities;
  17. 17 import org.openqa.selenium.support.ui.ExpectedCondition;
  18. 18 import org.openqa.selenium.support.ui.WebDriverWait;
  19. 19 import org.testng.Assert;
  20. 20 import org.testng.ITestResult;
  21. 21
  22. 22 import io.appium.java_client.AppiumDriver;
  23. 23 import io.appium.java_client.MultiTouchAction;
  24. 24 import io.appium.java_client.NoSuchContextException;
  25. 25 import io.appium.java_client.TouchAction;
  26. 26 import io.appium.java_client.android.AndroidDriver;
  27. 27 import io.appium.java_client.ios.IOSDriver;
  28. 28
  29. 29 /**
  30. 30  * [url=home.php?mod=space&uid=267564]@Author[/url] young   
  31. 31  * @description appium api封装
  32. 32  * */
  33. 33
  34. 34 public class AppiumUtil {
  35. 35     
  36. 36     public  AppiumDriver<WebElement> driver;
  37. 37     public     ITestResult it;
  38. 38     /**定义日志输出对象*/
  39. 39     public static Logger logger = Logger.getLogger(AppiumUtil.class);
  40. 40     
  41. 41     /**获取driver
  42. 42      * @throws  */
  43. 43     public AppiumDriver<WebElement> getDriver(String url,DesiredCapabilities capabilities,String platform){
  44. 44         
  45. 45             if(platform.equalsIgnoreCase("android")){
  46. 46             try {
  47. 47                 driver = new AndroidDriver<WebElement>(new URL(url), capabilities);
  48. 48             } catch (MalformedURLException e) {
  49. 49                 e.printStackTrace();
  50. 50             }
  51. 51             }else if(platform.equalsIgnoreCase("ios")){
  52. 52                 try {
  53. 53                     driver = new IOSDriver<WebElement> (new URL(url),capabilities);
  54. 54                 } catch (MalformedURLException e) {
  55. 55                     e.printStackTrace();
  56. 56                 }
  57. 57             }else{
  58. 58                 
  59. 59             }
  60. 60             return driver;
  61. 61  
  62. 62     }
  63. 63     
  64. 64     /**退出app*/
  65. 65     public void closeApp(String appName){
  66. 66         driver.closeApp();
  67. 67         logger.info(appName+"已经关闭");
  68. 68     }
  69. 69     
  70. 70     /**退出移动浏览器*/
  71. 71     public void quit(){
  72. 72         driver.quit();
  73. 73         logger.info("driver已被清理");
  74. 74     }
  75. 75     /**通过By对象 去查找某个元素*/
  76. 76     public WebElement findElement(By by){   
  77. 77         return driver.findElement(by);
  78. 78     }
  79. 79     
  80. 80     /**
  81. 81      * 通过By对象 去查找一组元素
  82. 82      * */
  83. 83     public List<WebElement> findElements(By by) {
  84. 84         return driver.findElements(by);
  85. 85     }
  86. 86     
  87. 87     /**清空元素内容*/
  88. 88     public void clear(By byElement){
  89. 89         WebElement element = findElement(byElement);
  90. 90         element.clear();
  91. 91         logger.info("清空元素:"+getLocatorByElement(element, ">")+"上的内容");
  92. 92     }
  93. 93     
  94. 94     /**输入内容*/
  95. 95     public void typeContent(By byElement,String str){
  96. 96         WebElement element = findElement(byElement);
  97. 97         element.sendKeys(str);
  98. 98         logger.info("在元素:"+getLocatorByElement(element, ">")+"输入内容:"+str);
  99. 99     }
  100. 100     /**点击*/
  101. 101     public void click(By byElement){
  102. 102         WebElement element = findElement(byElement);
  103. 103         try{
  104. 104         element.click();
  105. 105         logger.info("点击元素:"+getLocatorByElement(element, ">"));
  106. 106         }catch(Exception e){
  107. 107             logger.error("点击元素:"+getLocatorByElement(element, ">")+"失败", e);
  108. 108             Assert.fail("点击元素:"+getLocatorByElement(element, ">")+"失败", e);
  109. 109         }
  110. 110         
  111. 111     }
  112. 112     
  113. 113     /**查找一个元素 - appium新增的查找元素方法*/
  114. 114     public WebElement findElement(String locateWay,String locateValue){
  115. 115         WebElement element = null;
  116. 116     switch(locateWay){
  117. 117         
  118. 118     case "AccessibilityId":
  119. 119         element = driver.findElementByAccessibilityId(locateValue);
  120. 120         break;
  121. 121 //    case "AndroidUIAutomator":
  122. 122 //        element = driver.findElementByAndroidUIAutomator(locateValue);
  123. 123 //            break;
  124. 124     case "ClassName":
  125. 125         element = driver.findElementByClassName(locateValue);
  126. 126         break;
  127. 127     case "CSS":
  128. 128         element = driver.findElementByCssSelector(locateValue);
  129. 129         break;
  130. 130     case "ID":
  131. 131         element = driver.findElementById(locateValue);
  132. 132         break;
  133. 133     case "LinkText":
  134. 134         element = driver.findElementByLinkText(locateValue);
  135. 135         break;
  136. 136     case "Name":
  137. 137         element = driver.findElementByName(locateValue);
  138. 138         break;
  139. 139     case "PartialLinkText":
  140. 140         element = driver.findElementByPartialLinkText(locateValue);
  141. 141         break;
  142. 142     case "TagName":
  143. 143         element = driver.findElementByTagName(locateValue);
  144. 144         break;
  145. 145     case "Xpath":
  146. 146         element = driver.findElementByXPath(locateValue);
  147. 147         break;
  148. 148     default:
  149. 149         logger.error("定位方式:"+locateWay+"不被支持");
  150. 150         Assert.fail("定位方式:"+locateWay+"不被支持");
  151. 151         
  152. 152         }
  153. 153     return element;
  154. 154
  155. 155     }
  156. 156     
  157. 157     /**查找一组元素 - appium新增的查找元素方法*/
  158. 158     public List<?> findElements(String locateWay,String locateValue){
  159. 159         List<?> element=null;
  160. 160     switch(locateWay){
  161. 161         
  162. 162     case "AccessibilityId":
  163. 163         element = driver.findElementsByAccessibilityId(locateValue);
  164. 164         break;
  165. 165 //    case "AndroidUIAutomator":
  166. 166 //        element = driver.findElementsByAndroidUIAutomator(locateValue);
  167. 167 //            break;
  168. 168     case "ClassName":
  169. 169         element = driver.findElementsByClassName(locateValue);
  170. 170         break;
  171. 171     case "CSS":
  172. 172         element = driver.findElementsByCssSelector(locateValue);
  173. 173         break;
  174. 174     case "ID":
  175. 175         element = driver.findElementsById(locateValue);
  176. 176         break;
  177. 177     case "LinkText":
  178. 178         element = driver.findElementsByLinkText(locateValue);
  179. 179         break;
  180. 180     case "Name":
  181. 181         element = driver.findElementsByName(locateValue);
  182. 182         break;
  183. 183     case "PartialLinkText":
  184. 184         element = driver.findElementsByPartialLinkText(locateValue);
  185. 185         break;
  186. 186     case "TagName":
  187. 187         element = driver.findElementsByTagName(locateValue);
  188. 188         break;
  189. 189     case "Xpath":
  190. 190         element = driver.findElementsByXPath(locateValue);
  191. 191         break;
  192. 192     default:
  193. 193         logger.error("定位方式:"+locateWay+"不被支持");
  194. 194         Assert.fail("定位方式:"+locateWay+"不被支持");
  195. 195         
  196. 196         }
  197. 197     return element;
  198. 198
  199. 199     }
  200. 200     
  201. 201     /**获取文本1*/
  202. 202     public String getText(By by){
  203. 203         return findElement(by).getText().trim();
  204. 204     }
  205. 205     
  206. 206     
  207. 207     /**获取文本2*/
  208. 208     public String getText(String locateWay,String locateValue){
  209. 209         String str="";
  210. 210     switch(locateWay){
  211. 211         
  212. 212     case "AccessibilityId":
  213. 213         str = driver.findElementByAccessibilityId(locateValue).getText().trim();
  214. 214         break;
  215. 215 //    case "AndroidUIAutomator":
  216. 216 //        str = driver.findElementByAndroidUIAutomator(locateValue).getText().trim();
  217. 217 //            break;
  218. 218     case "ClassName":
  219. 219         str = driver.findElementByClassName(locateValue).getText().trim();
  220. 220         break;
  221. 221     case "CSS":
  222. 222         str = driver.findElementByCssSelector(locateValue).getText().trim();
  223. 223         break;
  224. 224     case "ID":
  225. 225         str = driver.findElementById(locateValue).getText().trim();
  226. 226         break;
  227. 227     case "LinkText":
  228. 228         str = driver.findElementByLinkText(locateValue).getText().trim();
  229. 229         break;
  230. 230     case "Name":
  231. 231         str = driver.findElementByName(locateValue).getText().trim();
  232. 232         break;
  233. 233     case "PartialLinkText":
  234. 234         str = driver.findElementByPartialLinkText(locateValue).getText().trim();
  235. 235         break;
  236. 236     case "TagName":
  237. 237         str = driver.findElementByTagName(locateValue).getText().trim();
  238. 238         break;
  239. 239     case "Xpath":

复制代码


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

x
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏
回复

使用道具 举报

该用户从未签到

4#
 楼主| 发表于 2018-3-14 14:35:03 | 只看该作者
  1. 99 capabilities.setCapability("platformVersion",platformVersion);
  2. 100 capabilities.setCapability("deviceName",deviceName);
  3. 101 capabilities.setCapability("sessionOverride", sessionOverride);
  4. 102 //如果测试平台是android的话,执行下面这个if语句内容
  5. 103 if(platformName.equalsIgnoreCase("android")){
  6. 104 /**
  7. 105 * 设置和android 测试相关的capability并实例化driver对象
  8. 106 * */
  9. 107 File app = new File(classpathRoot, androidAppPath);
  10. 108 capabilities.setCapability("app", app.getAbsolutePath());
  11. 109 capabilities.setCapability("unicodeKeyboard", unicodeKeyboard);
  12. 110 capabilities.setCapability("resetKeyboard", resetKeyboard);
  13. 111 capabilities.setCapability("automationName",automationName);
  14. 112 capabilities.setCapability("appPackage", appPackage);
  15. 113 capabilities.setCapability("appActivity", appActivity);
  16. 114 driver = appiumUtil.getDriver(serverURL, capabilities,platformName);
  17. 115 testContext.setAttribute("APPIUM_DRIVER", driver);
  18. 116 logger.info(PropertiesDataProvider.getTestData(appFilePath, appPackage)+"已经启动");
  19. 117 driver.manage().timeouts().implicitlyWait(elementTimeOut, TimeUnit.SECONDS);
  20. 118 return driver;
  21. 119
  22. 120 //如果测试平台是ios的话,执行下面这个if语句内容
  23. 121 }else if(platformName.equalsIgnoreCase("ios")){
  24. 122 /**
  25. 123 * 设置和ios 测试相关的capability并实例化driver对象
  26. 124 * */
  27. 125 File app = new File(classpathRoot, iosAppPath);
  28. 126 capabilities.setCapability("app", app.getAbsolutePath());
  29. 127 //ios设置自动接收系统alert,注意IOS弹出的alert,APPIUM可以自动处理掉,支持ios8以上系统
  30. 128 capabilities.setCapability("autoAcceptAlerts", true);
  31. 129 driver = appiumUtil.getDriver(serverURL, capabilities,platformName);
  32. 130 testContext.setAttribute("APPIUM_DRIVER", driver);
  33. 131 driver.manage().timeouts().implicitlyWait(elementTimeOut,TimeUnit.SECONDS);
  34. 132
  35. 133 }else{
  36. 134 logger.error("初始化driver失败");
  37. 135 Assert.fail("初始化driver失败");
  38. 136 }
  39. 137
  40. 138 //最后返回dirver对象
  41. 139 return driver;
  42. 140
  43. 141
  44. 142 }
  45. 143
  46. 144
  47. 145 }
  48. 复制代码
  49. 5.有时候我们不想把太多的配置放到testng.xml中,我们就需要根据key读取属性文件里面的value值,现在res/下创建properties,里面有app.properties 和config.properties 两个文本,然后在utils下写一个方法获取value的值,类为:PropertiesDataProvider,代码如下:


  50. 复制代码
  51. 1 package com.young.appiumcombat.utils;
  52. 2
  53. 3 import org.apache.commons.configuration.Configuration;
  54. 4 import org.apache.commons.configuration.ConfigurationException;
  55. 5 import org.apache.commons.configuration.PropertiesConfiguration;
  56. 6
  57. 7 /**
  58. 8 * @author young
  59. 9 * @Desription 从.properties文件中读取相关测试数据<br>
  60. 10 *
  61. 11 * */
  62. 12 public class PropertiesDataProvider {
  63. 13
  64. 14 public static String getTestData(String configFilePath, String key) {
  65. 15 Configuration config = null;
  66. 16 try {
  67. 17 config = new PropertiesConfiguration(configFilePath);
  68. 18 } catch (ConfigurationException e) {
  69. 19 e.printStackTrace();
  70. 20 }
  71. 21 return String.valueOf(config.getProperty(key));
  72. 22
  73. 23 }
  74. 24 }
  75. 复制代码
  76. 6.html报告插件

  77. 哈,我们使用 http://www.cnblogs.com/sunny-sl/p/7451582.html这里的arrow的报告插件,在将CONFIGFILE值修改成res/properties目录下的 config.properties,代码如下:


  78. 1 retrycount=0
  79. 2 sourcecodedir=com/young/appiumcombat/testcases
  80. 3 sourcecodeencoding=UTF-8
复制代码


回复 支持 反对

使用道具 举报

该用户从未签到

3#
 楼主| 发表于 2018-3-14 14:34:29 | 只看该作者
  1. 2.因为要显示log4日志,在pom.xml中加入jar包类:


  2. 1 <dependency>
  3. 2 <groupId>log4j</groupId>
  4. 3 <artifactId>log4j</artifactId>
  5. 4 <version>1.2.16</version>
  6. 5 <scope>provided</scope>
  7. 6 </dependency>
  8. 3.加载完成后要创建一个处理log类,名为:LogConfiguration类,代码如下:


  9. 复制代码
  10. 1 package com.young.appiumcombat.utils;
  11. 2 import java.util.Properties;
  12. 3
  13. 4 import org.apache.log4j.PropertyConfigurator;
  14. 5 /**
  15. 6  * @author young
  16. 7  * @decription 动态生成各个模块中的每条用例的日志,运行完成用例之后请到result/log目录下查看
  17. 8  * */
  18. 9 public class LogConfiguration {
  19. 10     
  20. 11         public static void initLog(String fileName){
  21. 12             //获取到模块名字
  22. 13             String founctionName = getFunctionName(fileName);
  23. 14             //声明日志文件存储路径以及文件名、格式
  24. 15             final String logFilePath  = "./result/logs/"+founctionName+"/"+fileName+".log";  
  25. 16             Properties prop = new Properties();
  26. 17             //配置日志输出的格式
  27. 18             prop.setProperty("log4j.rootLogger","info, toConsole, toFile");
  28. 19             prop.setProperty("log4j.appender.file.encoding","UTF-8" );
  29. 20             prop.setProperty("log4j.appender.toConsole","org.apache.log4j.ConsoleAppender");
  30. 21             prop.setProperty("log4j.appender.toConsole.Target","System.out");
  31. 22             prop.setProperty("log4j.appender.toConsole.layout","org.apache.log4j.PatternLayout ");
  32. 23             prop.setProperty("log4j.appender.toConsole.layout.ConversionPattern","[%d{yyyy-MM-dd HH:mm:ss}] [%p] %m%n");        
  33. 24             prop.setProperty("log4j.appender.toFile", "org.apache.log4j.DailyRollingFileAppender");
  34. 25             prop.setProperty("log4j.appender.toFile.file", logFilePath);
  35. 26             prop.setProperty("log4j.appender.toFile.append", "false");
  36. 27             prop.setProperty("log4j.appender.toFile.Threshold", "info");
  37. 28             prop.setProperty("log4j.appender.toFile.layout", "org.apache.log4j.PatternLayout");
  38. 29             prop.setProperty("log4j.appender.toFile.layout.ConversionPattern", "[%d{yyyy-MM-dd HH:mm:ss}] [%p] %m%n");
  39. 30             //使配置生效
  40. 31             PropertyConfigurator.configure(prop);
  41. 32
  42. 33         }
  43. 34         
  44. 35         
  45. 36         /**取得模块名字*/
  46. 37         public static String getFunctionName(String fileName){
  47. 38             String functionName = null;
  48. 39             int firstUndelineIndex = fileName.indexOf("_");
  49. 40             functionName = fileName.substring(0, firstUndelineIndex-4);
  50. 41             return functionName;
  51. 42         
  52. 43     }
  53. 44     
  54. 45
  55. 46 }
  56. 复制代码
  57. 4.因为我们要处理android和ios的项目,更方便处理兼容,在Utils中创建一个SelectDriver类,代码如下:


  58. 复制代码
  59.   1 package com.young.appiumcombat.utils;
  60.   2 import java.io.File;
  61.   3 import java.util.concurrent.TimeUnit;
  62.   4
  63.   5 import org.apache.log4j.Logger;
  64.   6 import org.openqa.selenium.WebElement;
  65.   7 import org.openqa.selenium.remote.DesiredCapabilities;
  66.   8 import org.testng.Assert;
  67.   9 import org.testng.ITestContext;
  68. 10
  69. 11 import io.appium.java_client.AppiumDriver;
  70. 12 /**
  71. 13  * @author Young
  72. 14  * @description 根据测试平台的不同生成不同的driver 比如AndroidDriver 或者是IOSDriver
  73. 15  *
  74. 16  * */
  75. 17
  76. 18 public class SelectDriver {
  77. 19     //声明driver
  78. 20     public  AppiumDriver<WebElement> driver;
  79. 21     //声明DesiredCapabilities
  80. 22     public DesiredCapabilities capabilities;
  81. 23     //声明ITestContext,用于获取testng配置文件内容
  82. 24     public ITestContext testContext;
  83. 25     //appium server地址
  84. 26     public String serverURL;
  85. 27     //测试引擎名字
  86. 28     public String automationName;
  87. 29     //测试平台名字
  88. 30     public String platformName;
  89. 31     //测试平台版本号
  90. 32     public String platformVersion;
  91. 33     //设备名字
  92. 34     public String deviceName;
  93. 35     //ios app的路径
  94. 36     public String iosAppPath;
  95. 37     //android app路径
  96. 38     public String androidAppPath;
  97. 39     //android app的 package
  98. 40     public String appPackage;
  99. 41     //android app的activity
  100. 42     public String appActivity;
  101. 43     //安卓独有 - 是否使用unicode键盘,使用此键盘可以输入中文字符
  102. 44     public boolean unicodeKeyboard;
  103. 45     //android独有 - 是否重置键盘,如果设置了unicodeKeyboard键盘,可以将此参数设置为true,然后键盘会重置为系统默认的
  104. 46     public boolean resetKeyboard;
  105. 47     //是否覆盖已有的seesssion,这个用于多用例执行,如果不设置的话,会提示前一个session还没有结束,用例就不能继续执行了
  106. 48     public boolean sessionOverride;
  107. 49     //暂停的等待时间
  108. 50     public int sleepTime;
  109. 51     //元素等待超时时间
  110. 52     public int elementTimeOut;
  111. 53     //app文件路径,主要存储的是app的名字
  112. 54     public String appFilePath;
  113. 55     //webview的名字或者叫标识符,一般以WEBVIEW开头,例如WEBVIEW_com.microsoft.bing
  114. 56     public final static String WEBVIEW_NAME = null;
  115. 57     //原生app的名字或者标识符,一般是NATIVE_APP
  116. 58     public final static String NATIVEAPP_NAME = null;
  117. 59     //实例化本类的日志输出对象
  118. 60     public static Logger logger = Logger.getLogger(SelectDriver.class);
  119. 61
  120. 62     public  AppiumDriver<WebElement> selectDriver(ITestContext context,AppiumUtil appiumUtil){
  121. 63           //通过testng的xml文件获取serverURL参数值,并赋给  serverURL变量
  122. 64           serverURL = context.getCurrentXmlTest().getParameter("serverURL");
  123. 65           //通过testng的xml文件获取automationName参数值,并赋给  automationName变量
  124. 66           automationName = context.getCurrentXmlTest().getParameter("automationName");
  125. 67           //通过testng的xml文件获取platformName参数值,并赋给  platformName变量
  126. 68           platformName = context.getCurrentXmlTest().getParameter("platformName");
  127. 69           //通过testng的xml文件获取platformVersion参数值,并赋给  platformVersion变量
  128. 70           platformVersion = context.getCurrentXmlTest().getParameter("platformVersion");
  129. 71           //通过testng的xml文件获取deviceName参数值,并赋给  deviceName变量
  130. 72           deviceName = context.getCurrentXmlTest().getParameter("deviceName");
  131. 73           //通过testng的xml文件获取androidAppPath参数值,并赋给  androidAppPath变量
  132. 74           androidAppPath = context.getCurrentXmlTest().getParameter("androidAppPath");
  133. 75           //通过testng的xml文件获取iosAppPath参数值,并赋给  iosAppPath变量
  134. 76           iosAppPath = context.getCurrentXmlTest().getParameter("iosAppPath");
  135. 77           //通过testng的xml文件获取appPackage参数值,并赋给  appPackage变量
  136. 78           appPackage = context.getCurrentXmlTest().getParameter("appPackage");
  137. 79           //通过testng的xml文件获取appActivity参数值,并赋给  appActivity变量
  138. 80           appActivity = context.getCurrentXmlTest().getParameter("appActivity");
  139. 81           //通过testng的xml文件获取unicodeKeyboard参数值,并赋给  unicodeKeyboard变量
  140. 82           unicodeKeyboard = Boolean.parseBoolean(context.getCurrentXmlTest().getParameter("unicodeKeyboard"));
  141. 83           //通过testng的xml文件获取resetKeyboard参数值,并赋给  resetKeyboard变量
  142. 84           resetKeyboard = Boolean.parseBoolean(context.getCurrentXmlTest().getParameter("resetKeyboard"));
  143. 85           //通过testng的xml文件获取sessionOverride参数值,并赋给  sessionOverride变量
  144. 86           sessionOverride = Boolean.parseBoolean(context.getCurrentXmlTest().getParameter("sessionOverride"));
  145. 87           //通过testng的xml文件获取sleepTime参数值,并赋给  sleepTime变量
  146. 88           sleepTime = Integer.valueOf(context.getCurrentXmlTest().getParameter("sleepTime"));
  147. 89           //通过testng的xml文件获取elementTimeOut参数值,并赋给  elementTimeOut变量
  148. 90           elementTimeOut = Integer.valueOf(context.getCurrentXmlTest().getParameter("elementTimeOut"));
  149. 91           //通过testng的xml文件获取appFilePath参数值,并赋给  appFilePath变量
  150. 92           appFilePath = context.getCurrentXmlTest().getParameter("appFilePath");
  151. 93           this.testContext = context;
  152. 94           capabilities = new DesiredCapabilities();
  153. 95           //告诉测试程序,当前项目目录在哪里
  154. 96           File classpathRoot = new File(System.getProperty("user.dir"));
  155. 97           //设置capability,以便和appium创建session
  156. 98           capabilities.setCapability("platformName",platformName);

复制代码


回复 支持 反对

使用道具 举报

该用户从未签到

2#
 楼主| 发表于 2018-3-14 14:33:27 | 只看该作者
  1. 240 str = driver.findElementByXPath(locateValue).getText().trim();
  2. 241 break;
  3. 242 default:
  4. 243 logger.error("定位方式:"+locateWay+"不被支持");
  5. 244 Assert.fail("定位方式:"+locateWay+"不被支持");
  6. 245
  7. 246 }
  8. 247 return str;
  9. 248
  10. 249 }
  11. 250
  12. 251 /**提交*/
  13. 252 public void submit(By by){
  14. 253 WebElement element=findElement(by);
  15. 254 try{
  16. 255 element.submit();
  17. 256 }catch(Exception e){
  18. 257 logger.error("在元素:"+getLocatorByElement(element, ">")+"做的提交操作失败",e);
  19. 258 Assert.fail("在元素:"+getLocatorByElement(element, ">")+"做的提交操作失败",e);
  20. 259 }
  21. 260 logger.info("在元素:"+getLocatorByElement(element, ">")+"做了提交操作");
  22. 261 }
  23. 262
  24. 263 /**
  25. 264 * 获得webview页面的标题
  26. 265 * */
  27. 266 public String getTitle() {
  28. 267 return driver.getTitle();
  29. 268 }
  30. 269
  31. 270 /**
  32. 271 * 获得元素 属性的文本
  33. 272 * */
  34. 273 public String getAttributeText(By elementLocator, String attribute) {
  35. 274 return findElement(elementLocator).getAttribute(attribute).trim();
  36. 275 }
  37. 276
  38. 277 /**
  39. 278 * 在给定的时间内去查找元素,如果没找到则超时,抛出异常
  40. 279 * */
  41. 280 public void waitForElementToLoad(int elementTimeOut, final By By) {
  42. 281 logger.info("开始查找元素[" + By + "]");
  43. 282 try {
  44. 283 (new WebDriverWait(driver, elementTimeOut)).until(new ExpectedCondition<Boolean>() {
  45. 284
  46. 285 public Boolean apply(WebDriver driver) {
  47. 286 WebElement element = driver.findElement(By);
  48. 287 return element.isDisplayed();
  49. 288 }
  50. 289 });
  51. 290 } catch (TimeoutException e) {
  52. 291 logger.error("超时!! " + elementTimeOut + " 秒之后还没找到元素 [" + By + "]");
  53. 292 Assert.fail("超时!! " + elementTimeOut + " 秒之后还没找到元素 [" + By + "]");
  54. 293
  55. 294 }
  56. 295 logger.info("找到了元素 [" + By + "]");
  57. 296 }
  58. 297
  59. 298 /**
  60. 299 * 判断文本是不是和需求要求的文本一致
  61. 300 * **/
  62. 301 public void isTextCorrect(String actual, String expected) {
  63. 302 try {
  64. 303 Assert.assertEquals(actual, expected);
  65. 304 } catch (AssertionError e) {
  66. 305 logger.error("期望的文字是 [" + expected + "] 但是找到了 [" + actual + "]");
  67. 306 Assert.fail("期望的文字是 [" + expected + "] 但是找到了 [" + actual + "]");
  68. 307
  69. 308 }
  70. 309 logger.info("找到了期望的文字: [" + expected + "]");
  71. 310
  72. 311 }
  73. 312
  74. 313 /**
  75. 314 * 暂停当前用例的执行,暂停的时间为:sleepTime
  76. 315 * */
  77. 316 public void pause(int sleepTime) {
  78. 317 if (sleepTime <= 0) {
  79. 318 return;
  80. 319 }
  81. 320 try {
  82. 321 TimeUnit.SECONDS.sleep(sleepTime);
  83. 322 logger.info("暂停:"+sleepTime+"秒");
  84. 323 } catch (InterruptedException e) {
  85. 324 e.printStackTrace();
  86. 325 }
  87. 326
  88. 327 }
  89. 328
  90. 329
  91. 330
  92. 331 /** 根据元素来获取此元素的定位值 */
  93. 332 public String getLocatorByElement(WebElement element, String expectText) {
  94. 333 String text = element.toString();
  95. 334 String expect = null;
  96. 335 try {
  97. 336 expect = text.substring(text.indexOf(expectText) + 1, text.length() - 1);
  98. 337 } catch (Exception e) {
  99. 338 e.printStackTrace();
  100. 339 logger.error("failed to find the string [" + expectText + "]");
  101. 340
  102. 341 }
  103. 342
  104. 343 return expect;
  105. 344
  106. 345 }
  107. 346
  108. 347
  109. 348 /**
  110. 349 * 判断实际文本时候包含期望文本
  111. 350 *
  112. 351 * @param actual
  113. 352 * 实际文本
  114. 353 * @param expect
  115. 354 * 期望文本
  116. 355 */
  117. 356 public void isContains(String actual, String expect) {
  118. 357 try {
  119. 358 Assert.assertTrue(actual.contains(expect));
  120. 359 } catch (AssertionError e) {
  121. 360 logger.error("The [" + actual + "] is not contains [" + expect + "]");
  122. 361 Assert.fail("The [" + actual + "] is not contains [" + expect + "]");
  123. 362 }
  124. 363 logger.info("The [" + actual + "] is contains [" + expect + "]");
  125. 364 }
  126. 365
  127. 366 /**跳转到webview页面*/
  128. 367 public void switchWebview(int index){
  129. 368 Set<String> contexts = driver.getContextHandles();
  130. 369 for (String context : contexts) {
  131. 370 System.out.println(context);
  132. 371 //打印出来看看有哪些context
  133. 372 }
  134. 373 driver.context((String) contexts.toArray()[index]);
  135. 374
  136. 375 }
  137. 376
  138. 377
  139. 378 /**跳转到webview页面*/
  140. 379 public void switchWebview(String contextName){
  141. 380 try{
  142. 381 Set<String> contexts = driver.getContextHandles();
  143. 382 for (String context : contexts) {
  144. 383 System.out.println(context);
  145. 384 //打印出来看看有哪些context
  146. 385 }
  147. 386 driver.context(contextName);
  148. 387 }catch(NoSuchContextException nce){
  149. 388 logger.error("没有这个context:"+contextName, nce);
  150. 389 Assert.fail("没有这个context:"+contextName, nce);
  151. 390 }
  152. 391
  153. 392 }
  154. 393
  155. 394
  156. 395 /**
  157. 396 * 执行JavaScript 方法
  158. 397 * */
  159. 398 public void executeJS(String js) {
  160. 399 ((JavascriptExecutor) driver).executeScript(js);
  161. 400 logger.info("执行JavaScript语句:[" + js + "]");
  162. 401 }
  163. 402
  164. 403 /**
  165. 404 * 执行JavaScript 方法和对象
  166. 405 * 用法:seleniumUtil.executeJS("arguments[0].click();", seleniumUtil.findElementBy(MyOrdersPage.MOP_TAB_ORDERCLOSE));
  167. 406 * */
  168. 407 public void executeJS(String js, Object... args) {
  169. 408 ((JavascriptExecutor) driver).executeScript(js, args);
  170. 409 logger.info("执行JavaScript语句:[" + js + "]");
  171. 410 }
  172. 411
  173. 412 /**检查元素是不是存在*/
  174. 413 public boolean doesElementsExist(By byElement){
  175. 414 try{
  176. 415 findElement(byElement);
  177. 416 return true;
  178. 417 }catch(NoSuchElementException nee){
  179. 418
  180. 419 return false;
  181. 420 }
  182. 421
  183. 422
  184. 423 }
  185. 424
  186. 425 /**长按操作*/
  187. 426 public void longPress(By by){
  188. 427 TouchAction tAction=new TouchAction(driver);
  189. 428 tAction.longPress(findElement(by)).perform();
  190. 429 }
  191. 430
  192. 431 /**滑动*/
  193. 432 public void swipe(int beginX,int beginY,int endX,int endY){
  194. 433 TouchAction tAction=new TouchAction(driver);
  195. 434 try{
  196. 435 tAction.press(beginX,beginY).moveTo(endX,endY).release().perform();
  197. 436 }catch(Exception e){
  198. 437 e.printStackTrace();
  199. 438 }
  200. 439 }
  201. 440
  202. 441 /**滚动 - 根据文本模糊匹配*/
  203. 442 public void scroll(String text){
  204. 443 driver.scrollTo(text);
  205. 444 }
  206. 445
  207. 446 /**滚动 - 根据文本精准匹配*/
  208. 447 public WebElement scrollExact(String text){
  209. 448 return driver.scrollToExact(text);
  210. 449 }
  211. 450
  212. 451 /**拖拽操作*/
  213. 452 public void DragAndDrop(By dragElement,By dropElement){
  214. 453 TouchAction act=new TouchAction(driver);
  215. 454 act.press(findElement(dragElement)).perform();
  216. 455 act.moveTo(findElement(dropElement)).release().perform();
  217. 456 }
  218. 457
  219. 458 /**放大和缩小*/
  220. 459 public void zoomAndPinch(int beginX,int beginY,int endX,int endY){
  221. 460 int scrHeight = driver.manage().window().getSize().getHeight();
  222. 461 int scrWidth = driver.manage().window().getSize().getWidth();
  223. 462 MultiTouchAction multiTouch = new MultiTouchAction(driver);
  224. 463 TouchAction tAction0 = new TouchAction(driver);
  225. 464 TouchAction tAction1 = new TouchAction(driver);
  226. 465 tAction0.press(scrWidth/2,scrHeight/2).waitAction(1000).moveTo(beginX,beginY).release();
  227. 466 tAction1.press(scrWidth/2,scrHeight/2+40).waitAction(1000).moveTo(endX,endY).release();
  228. 467 multiTouch.add(tAction0).add(tAction1);
  229. 468 multiTouch.perform();
  230. 469
  231. 470 }
  232. 471
  233. 472 /**app置于后台运行*/
  234. 473 public void runBackgound(int runTimes){
  235. 474 driver.runAppInBackground(runTimes);
  236. 475
  237. 476 }
  238. 477
  239. 478 /**收起键盘*/
  240. 479 public void hideKeyboard(){
  241. 480 driver.hideKeyboard();
  242. 481 logger.info("虚拟键盘已经收起");
  243. 482
  244. 483 }
  245. 484
  246. 485 /**安装app*/
  247. 486 public void instalApp(String appPath){
  248. 487 try{
  249. 488 driver.installApp(appPath);
  250. 489 }catch(Exception e){
  251. 490 logger.error("app安装失败",e);
  252. 491 Assert.fail("app安装失败",e);
  253. 492 }
  254. 493 }
  255. 494
  256. 495 /**app是否安装*/
  257. 496 public boolean isAppInstalled(String appPackage){
  258. 497
  259. 498 if(driver.isAppInstalled(appPackage)){
  260. 499 logger.info(appPackage+":已经安装");
  261. 500 return true;
  262. 501 }else {
  263. 502 logger.info(appPackage+":未安装");
  264. 503 return false;
  265. 504 }
  266. 505 }
  267. 506
  268. 507 /**页面过长时候滑动页面 window.scrollTo(左边距,上边距); */
  269. 508 public void scrollPage(int x,int y){
  270. 509 String js ="window.scrollTo("+x+","+y+");";
  271. 510 ((JavascriptExecutor)driver).executeScript(js);
  272. 511 }
  273. 512
  274. 513
  275. 514
  276. 515 }
复制代码


回复 支持 反对

使用道具 举报

本版积分规则

关闭

站长推荐上一条 /1 下一条

小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

GMT+8, 2024-9-28 11:17 , Processed in 0.086324 second(s), 26 queries .

Powered by Discuz! X3.2

© 2001-2024 Comsenz Inc.

快速回复 返回顶部 返回列表