Search code examples
c#selenium-webdriver

Verifying a checkbox is checked with C# & Selenium is failing


I'm working with C#.NET and Selenium and am attempting to verify whether or not a checkbox is checked. It fails every time. Here's the code:

public static void verifyCheckboxIsChecked(WebDriver driver, System.String xPath)
{
    Thread.Sleep(2000);
    // checkbox should be checked
    IWebElement element = driver.FindElement(By.XPath(xPath));
    if (element.Selected)
    {

        Logger("Test passed, checkbox is checked!");
    }
    else
    {
        Logger("Test failed, checkbox is NOT checked!");
    }
}

The full XPath I'm passing into this method is absolutely correct. It finds the checkbox. element.Selected is coming back False every time.

Is there another way to do this, like an attribute I can get? Frustrated. This was easy in Java but I have no access to isChecked() in C#. Any help appreciated.


Solution

  • Is there another way to do this, like an attribute I can get?

    Try element.GetAttribute("checked")

    The GetAttribute(string) method will return the current value of the attribute, even if the value has been modified after the page has been loaded. Note that the value of the following attributes will be returned even if there is no explicit attribute on the element

    docs