2016-07-25 131 views
0

我想在我的android設備上打開一個移動.apk文件,然後選擇一個國家「USA」並點擊「保存」按鈕。Android應用程序自動化腳本:通過Appium,Selenium WebDriver,Java:NoSuchElementFoundException

import java.io.File; 
import java.net.MalformedURLException; 
import java.net.URL; 

import org.openqa.selenium.By; 
import org.openqa.selenium.remote.DesiredCapabilities; 
import org.testng.annotations.Test; 

import io.appium.java_client.android.AndroidDriver; 

public class DemoC { 

AndroidDriver driver =null; 
DesiredCapabilities capabilities; 
File app = new  File("C:\\Users\\310250972\\workspace\\DreamMapper_2.5_Alpha_July_5_65.apk"); 

@Test(priority=1) 
public void invokeApp() throws MalformedURLException 
{ 
capabilities = new DesiredCapabilities(); 
capabilities.setCapability("automationName","Appium"); 
capabilities.setCapability("platformName","Android"); 
capabilities.setCapability("platformVersion","6.0.1"); 
capabilities.setCapability("deviceName","Galaxy S6"); 

capabilities.setCapability("app", app.getAbsolutePath()); 

//capabilities.setCapability("appPackage","com.philips.sleepmapper.root"); 
//capabilities.setCapability("appactivity","com.philips.sleepmapper.activity.SplashScreenActivity"); 

driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); 

} 

@Test(priority=2) 
public void selectCountry() throws InterruptedException{ 
Thread.sleep(20000); 
//driver.findElement(By.xpath("//android.widget.TextView[Contain]")) 
driver.findElement(By.xpath("//android.widget.TextView[contains(@text='United States')]")).click(); 
Thread.sleep(10000); 
driver.findElement(By.xpath("//android.widget.TextView[contains(@text='Save')]")).click(); 
// driver.findElement(By.name("Save")).click(); 
} 

}[I want to select "United States" and click on "Save" button][1] 

//執行時,測試方法「selectCountry()」失敗。 Nosuchelementfoundexception

回答

1

當您使用帶有contains的Xpath查詢時,您將需要使用逗號分隔符而不是等號。

所以,你的步驟應該是這樣的:

driver.findElement(By.xpath("//android.widget.TextView[contains(@text, 'United States')]")).click(); 
Thread.sleep(10000); 
driver.findElement(By.xpath("//android.widget.TextView[contains(@text, 'Save')]")).click(); 

如果這沒有幫助,你可以嘗試使用driver.getPageSource();確保元素實際上存在與預期值@Text。該命令返回所有現有元素,並可用於驗證元素是否存在正確的屬性。

0

儘可能避免使用Thread.sleep(),因爲它告訴等待測試時使用具有不同因特網速度或不同文件大小等因素的測試場景時的確切時間。改爲使用WebDriverWait

WebDriverWait wait = new WebDriverWait(driver, 60); 
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.TextView[contains(@text='United States')]").cick(); 

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.TextView[contains(@text='Save')]")).click(); 

WebDriverWait告訴appium等待一定量的時間(在該代碼其60 seconds)或用於ExpectedConditions得到滿足。

相關問題