我正在使用Cucumber Automation框架进行练习,以便我可以将其用于工作中的项目。我正在使用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,标题是我所期望的。但是硒没有返回正确的结果。有人可以向我解释为什么以及我如何修复它?
答案:
可能需要添加一些等待时间,然后才主张页面标题,因为有时驱动程序的操作很快,这可能会导致断言失败
@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));
}