如何检查复选框是否启用?

Vid*_*ids 2 testng selenium

如何勾选复选框是否启用?在 selenium + Testng 中,在应用程序中单击复选框将被启用,我需要验证复选框是否已启用。提前谢谢。

Sub*_*ubh 6

有一种方法“isEnabled()”,用于检查 WebElement 是否已启用。您可以使用以下代码进行检查;

boolean enabled = driver.findElement(By.xpath("//xpath of the checkbox")).isEnabled();
Run Code Online (Sandbox Code Playgroud)

我在上面使用了 xpath,但您也可以使用 id 或 cssselector 来定位元素。

上面的代码将返回 'true',如果相关的 WebElement,即在您的情况下启用了复选框,否则它将返回 'false'

而且,如果您想检查复选框是否被选中/选中,您可以使用“isSelected()”方法,您可以像这样使用;

boolean checked = driver.findElement(By.xpath("//xpath of the checkbox")).isSelected();
Run Code Online (Sandbox Code Playgroud)

上面的代码将返回 'true',如果相关的 WebElement,即在您的情况下,复选框被选中,否则它将返回 'false'


在评论中获取您的代码片段,我想出了以下方法:-

如果复选框被选中,这将返回一个字符串“通过”,如果未选中或在执行此代码时出现任何错误,则返回“失败”。

public static String isCheckBoxChecked(String objlocator, String elemName) {

        APP_LOGS.debug("Checking if the checkbox related to '"+elemName+"' is checked or not.");
        System.out.println("Checking if the checkbox related to '"+elemName+"' is checked or not.");

        try {

            findWebElement(objlocator);

            //Assuming the objLocator contains xpath
            if (driver.findElement(By.xpath(objlocator)).isSelected()) {
                System.out.println("Checkbox related to: '"+elemName+"' is checked.");
                APP_LOGS.debug("Checkbox related to: '"+elemName+"' is checked.");
            }else{
                System.out.println("Checkbox related to: '"+elemName+"' is not checked!!");
                APP_LOGS.debug("Checkbox related to: '"+elemName+"' is not checked!!");
                return "Fail" + ": Checkbox related to: '"+elemName+"' is not checked!!";
            }
        }
        catch (Throwable t) {
            System.out.println("Error while Checking if the checkbox related to '"+elemName+"' is checked or not. -" + t.getMessage());
            APP_LOGS.error("Error while Checking if the checkbox related to '"+elemName+"' is checked or not. -" + t.getMessage());
            return "Fail"+": Error while Checking if the checkbox related to '"+elemName+"' is checked or not. -" + t.getMessage();
        }

        return "Pass"+": Checkbox related to: '"+elemName+"' is checked.";
    }
Run Code Online (Sandbox Code Playgroud)