Seleniumjava:如果元素不存在,如何失败测试



从Selenium/CCucumber开始,我想检查应用程序中是否存在元素(h1标题(。为此,我在编写这种方法时从以下代码中获得了灵感:

@Then("the admin arrives on the clients/prospects dashboard")
public boolean the_admin_arrives_on_the_clients_prospects_dashboard() {
return driver.findElements(By.xpath("//h1[contains(text(), 'Dashboard')]")).size() != 0;
}

但是,如果元素不存在,我希望我的测试失败。该方法返回";false";值是否足以使测试失败?非常感谢

list.size() != 0返回false表示列表不包含任何元素。

它明确地验证元素是否存在

在Michael Mintz的帮助下,以下是如何在Cucumber中进行断言。

注意:您需要在步骤定义文件中导入Junit.Assert

@Then("the admin arrives on the clients/prospects dashboard")
public boolean the_admin_arrives_on_the_clients_prospects_dashboard() {
assertFalse(driver.findElements(By.xpath("//h1[contains(text(), 'Dashboard')]")).size() != 0);
}

您可以使用isEmpty((方法进行检查:

public boolean isElementPresented(final By locator) {
return webDriver.findElements(locator).isEmpty();
}