gpt4 book ai didi

java - Selenium 如果元素不存在,如何使测试不失败(java)

转载 作者:行者123 更新时间:2023-11-30 06:39:55 25 4
gpt4 key购买 nike

我正在尝试通过一个元素不存在的测试(由于用户访问),然后它将被写入范围报告,但我不断收到“没有此类元素异常”。

我的代码是这样的:

if (homePage.cloudAdminApp.isDisplayed())
{
test.log(LogStatus.PASS, getData("USER") +" have o/cloud admin application access but it shoudn't have");
}
else
{
test.log(LogStatus.PASS, getData("USER") +" have not o/cloud admin application access");
}

我也尝试过这样做:

  • 添加trycatch (NoSuchElementException e)但测试一直失败。
  • 添加而不是 if一个Assert.assertNull

没有一个有效。

我做错了什么?

最佳答案

如果网页上没有元素findElement将返回NoSuchElementException

FindElements 将返回空列表,因此您可以尝试这种方式

List<WebElement> elements = driver.findElements(By.locator);

if(elements.size()>0)
{
elements.get(0).click()
}

另一种方法是将代码正确地包含在 try catch block 中

例如

try
{
driver.findElement(By.locator).click();
}
catch(Exception e)
{
System.out.println("No Element");
// write your code here for action have to do if element is not there
}

关于java - Selenium 如果元素不存在,如何使测试不失败(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44542327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com