我正在尝试使用 ExpectedConditions 类来执行与 Selenium 相关的断言,但我无法找到断言给定元素不存在的事实上的最佳实践。我正在尝试使用这样的东西......
Assert.assertFalse(ExpectedConditions.presenceOfElementLocated(By.xpath(myXpath)).apply(driver1));
但这当然不会编译,因为 presenceOfElementLocated
返回 WebElement 而不是 boolean 值,这让我很沮丧。你推荐什么作为实现我想要的最佳实践?
编辑: 已接受的问题答案已转换为 Java ...
public static boolean elementXpathPresent(WebDriver driver,String elementXpath) {
try {
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(elementXpath)));
} catch (TimeoutException e) {
return false;
}
return true;
}
最佳答案
好吧,如果不存在匹配选择器的 element
,使用 ExpectedConditions
最终将抛出 NoSuchElementException
。在这种情况下,您可能希望将 try catch 与 ExpectedConditions
一起使用,或者简单地使用 findElements()
和 size()
来查看它是否找到任何元素根本。看我的回答here
这是您的另一种选择。用 C# 编写,但转换起来相当容易
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool Test()
{
try
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(
ExpectedConditions.ElementExists(By.XPath("MyXpath")));
}
catch (NoSuchElementException)
{
return false;
}
return true;
}
/// <summary>
///
/// </summary>
public void Assertion()
{
Assert.IsTrue(Test());
}
关于java - 使用 ExpectedConditions 类断言元素不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28504546/