我正在尝试使用关键字在Google中搜索,然后断言第四个搜索结果是特定单词 我已经在google chrome上尝试了相同的代码,并且可以正常工作 但在Firefox中无法使用相同的代码
public class Task4_Class {
WebDriver driver;
@BeforeClass
public void beforeClass() {
System.getProperty("webdriver.gecko.driver","src\\test\\resources\\Drive\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
}
@AfterClass
public void afterClass() {
//driver.close();
}
@BeforeMethod
public void beforeMethod() {
driver.navigate().to("https://www.google.com/ncr");
}
@Test
public void searchInGoogleAndAssertTheFourthResult() {
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("TestNG");
searchBox.sendKeys(Keys.ENTER);
List <WebElement> results = driver.findElements(By.className("ellip"));
String fourthResult = results.get(3).getText();
Assert.assertEquals(fourthResult, "TestNG Tutorial");
}
}
答案 0 :(得分:0)
您的测试不是在等待结果出现,因此它将填充空白列表,因为页面尚未完全加载。我更新了您的代码以引入WebDriverWait
,还更新了您的XPath定位器,使其更强大。我测试了此功能,并成功检索了第四个搜索结果。
@Test
public void searchInGoogleAndAssertTheFourthResult() {
WebElement searchBox = driver.findElement(By.XPath("q"));
searchBox.sendKeys("TestNG");
searchBox.sendKeys(Keys.ENTER);
// wait for elements to exist
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.XPath("//a/h3/div")));
// get list of search result elements
List <WebElement> results = driver.findElements(By.XPath("//a/h3/div"));
String fourthResult = results.get(3).getText();
// The exact title is not just "TestNG Tutorial", there is more text
// need to change this to a contains
Assert.assertTrue(fourthResult.contains("TestNG Tutorial"));
// this one will not work
Assert.assertEquals(fourthResult, "TestNG Tutorial");
}
}
请注意,您的Assert.assertEquals
语句将失败,因为没有任何搜索结果与“ TestNG Tutorial”完全匹配。他们也有其他文字,例如“ TestNG教程:注释,框架,...中的示例”。因此,您应该改为针对contains
查询运行断言。