验证检查按钮不可用

2wnc66cl  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(258)

我使用此代码检查按钮是否存在:

protected void validateButtonPresence(WebDriver driver, String buttonId, String name) {
        List<WebElement> resultList = driver.findElements(By.id(buttonId));
        if(resultList.size() == 0)
        {
            try
            {
                throw new Exception("Button " + buttonId + " is not found!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

我需要确认按钮不存在。如何修改代码,使其检查按钮是否不存在?

huwehgph

huwehgph1#

您的代码非常接近您要查找的内容,因为元素的存在和不存在是相同的逻辑,只是符号相反。

protected void validateButtonAbsence(WebDriver driver, String buttonId) {
    List<WebElement> resultList = driver.findElements(By.id(buttonId));
    if(resultList.size()! = 0)
    {
       throw new Exception("Button " + buttonId + " is present!");
    }
}

您还可以返回布尔值,而不是引发异常,如下所示:

protected boolean validateElementAbsence(WebDriver driver, String elementId) {
    return (driver.findElements(By.id(elementId)).size == 0);
}
kxxlusnw

kxxlusnw2#

当你写作时 validateButtonPresence 方法,通过名称本身,它表示这是一个验证方法。验证方法应始终返回布尔值,要么验证失败,要么正确通过?
示例代码:

protected boolean validateButtonPresence(WebDriver driver, String buttonId) {
    boolean flag = false;
    try {
        if(!driver.findElement(By.id(buttonId)).isDisplayed()) {
            throw new Exception("Button " + buttonId + " is not found!");
        }
        else {
            System.out.println("Button is displayed on the page.");
            flag = true;
        }   
    }
    catch (NoSuchElementException e) {
        return flag;
    } 
    catch (StaleElementReferenceException e) {
        return flag;
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    return flag;
}

我相信通过引入 ExplicitWaits .

相关问题