Android应用程序自动化脚本:通过Appium,Selenium WebDriver,Java:NoSuchElementFoundException

时间:2016-07-25 09:34:31

标签: java android selenium-webdriver appium

我正在尝试在我的Android设备中打开移动.apk文件,然后选择一个国家" USA"然后点击"保存"按钮。

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

2 个答案:

答案 0 :(得分: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值一致。该命令返回所有现有元素,可用于验证元素是否存在正确的属性。

答案 1 :(得分: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