如何不失败等待直到(预期条件)



我有一个表格,可能会也可能不会根据URL显示。现在我的测试循环遍历所有给定的 URL。我必须单击一个搜索按钮,然后验证表是否存在。 即使表格清晰可见,我的表最初也失败了。我添加了以下代码来处理该问题:

WebDriverWait wait = new WebDriverWait(data.Driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("abc")));
Boolean tableVisibility = data.Driver.findElements(By.id("12345abcd")).size() > 0;
if (tableVisibility == true) {
result.logInfo("table displaying successfully");
}
Boolean isElmPresent =  data.Driver.findElements(By.id("labelMessage")).size() > 0;
if (isPresent == true) {
this.updateDBTbl(abc,xyz);
}

这句话帮助我解决了表加载的问题。但是现在我遇到了找不到表的问题。实际上,当找不到表时,我们会得到一个新标签,上面提到"我们需要联系系统台",我需要在我的数据库中报告。但是在 wait.till 语句的情况下,当它在 30 秒后看不到表时,它会出错并停止执行。因此,标签永远不会得到验证。我现在已经注释掉了wait.till 语句,而是添加了解决了该问题的 Thread.Sleep,但我根本不喜欢硬等待。所以我想知道是否有更好的方法来解决这个问题。

试试这个:

try{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("abc")));
Boolean tableVisibility = data.Driver.findElements(By.id("12345abcd")).size() > 0;
if (tableVisibility==true) {
result.logInfo("table displaying successfully");
}
Boolean isElmPresent=  data.Driver.findElements(By.id("labelMessage")).size() > 0;
if (isPresent == true) {
this.updateDBTbl(abc,xyz);
}
}catch(ElementNotVisibleException e){
e.printStackTrace();
}

这将解决您的问题。

您的逻辑流程需要稍作调整。您需要:

  1. 等待表出现
    1. 如果存在,则记录成功
    2. 如果不存在,则记录失败和日志标签消息

// not sure what this does
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("abc")));
// is table present?
try
{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("12345abcd")));
result.logInfo("table displaying successfully");
}
catch (TimeoutException e)
{
// table is not present
result.logInfo("table NOT displaying successfully");
// report contact system desk message
if (data.Driver.findElements(By.id("labelMessage")).size() > 0)
{
this.updateDBTbl(abc,xyz);
}
}

以下是您可以尝试的解决方案: 1.检查元素是否可见 - 如果可见,则对其执行操作,如果不是 - 则对表不存在时应显示的其他元素执行操作 2. 在等待中添加忽略异常 3. 包装 try/catch 块以处理表的缺失

最新更新