AndroidContactsTest.java
以下代码使用ContactManager.apk进行测试
1 package com.saucelabs.appium; 2 3 import io.appium.java_client.AppiumDriver; 4 import io.appium.java_client.android.AndroidDriver; 5 import io.appium.java_client.android.AndroidElement; 6 import org.junit.After; 7 import org.junit.Before; 8 import org.junit.Test; 9 import org.openqa.selenium.By; 10 import org.openqa.selenium.WebElement; 11 import org.openqa.selenium.remote.DesiredCapabilities; 12 13 import java.io.File; 14 import java.net.URL; 15 import java.util.List; 16 17 public class AndroidContactsTest { 18 private AppiumDriver<AndroidElement> driver;// driver用AppiumDriver声明。 19 20 @Before 21 public void setUp() throws Exception { 22 // set up appium 23 //File classpathRoot = new File(System.getProperty("user.dir")); 24 File appDir = new File( "E:/package"); 25 File app = new File(appDir, "ContactManager.apk"); 26 DesiredCapabilities capabilities = new DesiredCapabilities(); 27 capabilities.setCapability("deviceName","Honor6"); //deviceName必须有,但是值可以随意写。 28 capabilities.setCapability("platformVersion", "4.4"); 29 capabilities.setCapability("app", app.getAbsolutePath()); 30 capabilities.setCapability("appPackage", "com.example.android.contactmanager");//使用adb shell获取package和activity,详见 31 capabilities.setCapability("appActivity", ".ContactManager"); 32 driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);//driver用AndroidDriver赋值。 33 } 34 35 @After 36 public void tearDown() throws Exception { 37 driver.quit(); 38 } 39 40 @Test 41 public void addContact(){ 42 WebElement el = driver.findElement(By.xpath(".//*[@text='Add Contact']"));//在iOS环境下,可以使用appium的inspector轻松定位元素,甚至直接得到xpath;但是对于Android环境,appium的inspector有很多限制。因此,需要使用UIAutomatorviewer定位元素。 43 el.click(); 44 List<AndroidElement> textFieldsList = driver.findElementsByClassName("android.widget.EditText"); 45 textFieldsList.get(0).sendKeys("Some Name"); 46 textFieldsList.get(2).sendKeys("Some@example.com"); 47 driver.swipe(100, 500, 100, 100, 2); //猜测这个swipe是为了显示出被键盘遮挡住的save按钮,可以用driver.hideKeyboard();替代。 48 driver.findElementByXPath(".//*[@text='Save']").click(); 49 } 50 51 }
用到的元素定位方式:
Xpath : WebElement el = driver.findElement(By.xpath(".//*[@text='Add Contact']"));
ClassName: List<AndroidElement> textFieldsList = driver.findElementsByClassName("android.widget.EditText");
用到的操作:
click: driver.findElementByXPath(".//*[@text='Save']").click();
sendKeys: textFieldsList.get(0).sendKeys("Some Name");
swipe: driver.swipe(100, 500, 100, 100, 2);