【问题标题】:Googling in Selenium WebDriver, trying to verify result; result comes back as false when true在 Selenium WebDriver 中搜索,尝试验证结果;结果返回为假时为真
【发布时间】:2014-07-09 13:48:27
【问题描述】:

我正在尝试编写一个 Selenium WebDriver 测试,该测试导航到 Google,搜索某些内容,然后验证 Google 是否搜索了输入的内容。但是,当我可以看到时,下面的代码给出了“假”输出这是真的。

我能为这种情况找到的所有代码似乎都是 Google Instant 之前的代码,我无法在 FirefoxDriver 中关闭 Instant。在检查任何内容之前,它还应该等待带有 Web、图像、视频等的栏可点击;增加implicitlyWait 值似乎对测试的结果或其最终结果没有任何影响。在 verifyTrue 和 assertTrue 之间切换不会改变结果。

如果答案很明显,我深表歉意,但我对 Selenium WebDriver(和 Java)比较陌生。

package mypackage;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;

public class NavigateSearchVerify {

    public static void main(String[] args) {

        WebDriver driver = new FirefoxDriver();
        String baseUrl = "http://www.google.com";
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

        driver.get(baseUrl);

        WebElement query = driver.findElement(By.name("q"));
        query.sendKeys("Hello");
        query.sendKeys(Keys.ENTER);

        WebDriverWait wait = new WebDriverWait(driver, 15);
        wait.until(ExpectedConditions.elementToBeClickable(By.id("top_nav")));

        Boolean assertTrue = driver.findElements(By.className("gbqfif")).contains("Hello");
        if (assertTrue == true) {
            System.out.print("Yes");
        } else {
            System.out.print("No");
        }    
    }    
}

【问题讨论】:

    标签: java selenium-webdriver


    【解决方案1】:

    在检查您的问题和代码时,这是我的理解:-

    1. 你要打开谷歌
    2. 在搜索框中输入“你好”
    3. 按回车
    4. 验证是否在搜索框中输入了“Hello”

    driver.findElements(By.className("gbqfif")).contains("Hello"); 不正确。

    className("gbqfif") 的元素超过 4 个。因此,当您使用 findElements() 时,将返回 WebElement 列表。您正在检查此列表是否包含“Hello”字符串对象。但该列表包含 WebElement 对象。

    改用以下代码: driver.findElement(By.name("q")).getAttribute("value").contains("Hello");

    如果这对你有帮助,请告诉我。

    【讨论】:

      【解决方案2】:

      你通过调试看到它是真的吗?

      在您的 Boolean assertTrue 开始时替换这些行并尝试以下操作:

      if(waitForTextToLoad(By.className("gbqfif"),"Hello")){
         System.out.println("Yes");
      }else{
         System.out.println("Yes");
      }
      

      并将以下内容从您的主要内容中删除:

      public boolean waitForTextToLoad(By by, String text){
              boolean wbeWaitFor = (new WebDriverWait(driver,10))
                      .until(ExpectedConditions.textToBePresentInElementLocated(by, text));
              return wbeWaitFor;
          }
      

      【讨论】:

        猜你喜欢
        • 2023-03-10
        • 2022-01-12
        • 1970-01-01
        • 2017-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多