Selenium Webdriver中的IF语句

时间:2015-03-18 17:19:26

标签: java selenium

我想知道是否有人可以帮助我解决我尝试解决的问题以及Java for Webdriver中的If语句。

登录我正在测试的应用程序时,可以将其带到主页面之前的安全问题页面(如果是新用户等)。我想在我的测试中做的代码是,如果出现安全问题页面填写并继续,如果没有检查你在主页上。

我能够使用

在Selenium RC中完成此操作
 if (selenium.isTextPresent("User Account Credentials Update")) {   
            selenium.type("//input[@id='securityQuestion']", "A");
            selenium.type("//input[@id='securityAnswer']", "A");
            selenium.type("//input[@id='emailAddress']", "test@test.com");
            selenium.click("update");
            selenium.waitForPageToLoad("30000");
            }


 assertTrue(selenium.isTextPresent("MainPage"));

使用我正在使用的Webdriver:

    if(driver.findElement(By.id("securityQuestion")) != 0) {
                driver.findElement(By.id("securityQuestion")).sendKeys("A");
                driver.findElement(By.id("securityAnswer")).sendKeys("A");
                driver.findElement(By.id("emailAddress")).sendKeys("test@test.com");
                driver.findElement(By.id("update")).click();

Assert.assertTrue("Main Page is not Showing",
            driver.getPageSource().contains("MainPage"));

问题在于,如果未显示“安全性”屏幕,它总是会发生异常。我如何设置代码,以便在没有显示该页面时忽略安全页面的内容? 感谢您的帮助: - )

3 个答案:

答案 0 :(得分:2)

您可以使用driver.findElements来检查特定元素是否存在而不会抛出异常。这是有效的,因为如果没有找到元素,它将返回WebElements的大小为0的列表。目前,如果Selenium尝试使用findElement查找元素并且该元素不存在,则会抛出NoSuchElementException这意味着您可以替换:

if (driver.findElement(By.id("securityQuestion")) != 0)

用这个:

if (driver.findElements(By.id("securityQuestion")).size() != 0)

答案 1 :(得分:2)

只要你捕获/处理它就会抛出异常。

换句话说,我在这里关注EAFP approach

try {
    driver.findElement(By.id("securityQuestion"));
    // ...
} catch (NoSuchElementException e) {
    // handle exception, may be at least log in your case
}

答案 2 :(得分:0)

我通常只是把它包装成一个方法:

public boolean elementExists(By selector)
{
    try
    {
        driver.findElement(selector)
        return true;
    }
    catch(NoSuchElementException e)
    {
        return false;
    }
}