我正在使用Cucumber自动化框架,所以我可以将它用于工作中的项目。我使用Selenium WebDriver与浏览器进行交互。现在我只是测试Google搜索确实会返回正确的结果。我的功能文件在这里:
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",而不是预期的"马 - Google搜索"。
我不确定为什么要这样做。我已经检查了结果页面的HTML,标题就是我的预期。但是Selenium没有返回正确的结果。有人可以向我解释为什么以及如何解决它?
答案 0 :(得分:-1)
答案:
可能你需要在断言页面标题之前添加一些等待时间,因为有时候驱动程序操作非常快,可能导致断言失败
@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));
}