Java Selenium WebDriver赢得';t返回Google结果页面的正确标题

Java Selenium WebDriver赢得';t返回Google结果页面的正确标题,java,selenium,junit,cucumber,Java,Selenium,Junit,Cucumber,我正在练习Cucumber自动化框架,以便在工作中使用它。我正在使用SeleniumWebDriver与浏览器交互。现在我只是在测试谷歌搜索是否返回正确的结果。我的功能文件在这里: Feature: Google Scenario: Google search Given I am on the Google home page When I search for "horse" Then the results should relat

我正在练习Cucumber自动化框架,以便在工作中使用它。我正在使用SeleniumWebDriver与浏览器交互。现在我只是在测试谷歌搜索是否返回正确的结果。我的功能文件在这里:

Feature: Google

    Scenario: Google search
        Given I am on the Google home page
        When I search for "horse"
        Then the results should relate to "horse"
这是我的Java类,包含步骤定义:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.junit.Assert;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class StepDefinitions {

    WebDriver driver = null;

    @Given("^I am on the Google home page$")
        public void i_am_on_the_Google_home_page() throws Throwable {
        driver = new FirefoxDriver();
        driver.get("https://www.google.com");
    }

    @When("^I search for \"([^\"]*)\"$")
    public void i_search_for(String query) throws Throwable {
        driver.findElement(By.name("q")).sendKeys(query);
        driver.findElement(By.name("btnG")).click();
    }

    @Then("^the results should relate to \"([^\"]*)\"$")
    public void the_results_should_relate_to(String result) throws Throwable {
        System.out.println(driver.getTitle());
        Assert.assertTrue(driver.getTitle().contains(result));
    }
 }
为了测试它是否返回相关结果,我只是断言页面标题包含搜索查询。现在,它没有通过最后一步,因为
driver.getTitle()
返回的是“Google”,而不是预期的“horse-Google搜索”

我不知道它为什么这样做。我已经检查了结果页面的HTML,标题是我所期望的。但硒并没有返回正确的结果。有人能给我解释一下为什么以及如何修复它吗?

回答:

在断言页面标题之前,可能需要添加一些等待时间,因为有时驱动程序操作非常快,这可能会导致断言失败

@Then("^the results should relate to \"([^\"]*)\"$")
    public void the_results_should_relate_to(String result) throws Throwable {
        WebDriverWait wait = new WebDriverWait(driver, 10);
        WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("some element in page"))));
        System.out.println(driver.getTitle());
        Assert.assertTrue(driver.getTitle().contains(result));
    }

它是否返回上一页的标题?它可能在页面转换完成之前返回页面标题。很抱歉,我不知道Cucumber,因此无法提供代码,但您可以尝试插入一个等待,看看这是否解决了问题。该
.implicitlyWait()
并没有像您认为的那样执行。该行设置了全局等待时间。。。它不会仅在该位置等待10秒。我不熟悉Cucumber,但在Java/C中,您需要的是WebDriverWait。我在Cucumber中找到了一个参考可能解决方案的页面。我已经更新了我的答案。。我的意思是在断言页面标题WebDriverWait之前等待一段时间,这是正确的方法。。。。我会删除Thread.sleep()选项,因为这不是一个好的做法。