TestRaptor TestRaptor - 1 year ago 48
Java Question

How can I verify an attribute is present in an element?

I have many radio buttons on my screen. When a radio button is selected, it has an attribute of checked. When the radio button is not selected, the checked attribute is not present. I would like to create a method that would pass if the element is not present.

I am using selenium webdriver and java. I know I can retrieve attributes by using

. I'm just not sure how to verify that an attribute does not exist, and for the test to pass when it doesn't exist (fail if it does exist).

When the radio button is checked

<input id="ctl00_cphMainContent_ctl00_iq1_response_0" type="radio" name="ctl00$cphMainContent$ctl00$iq1$response" value="1" checked="checked">

When the radio button is not checked

<input id="ctl00_cphMainContent_ctl00_iq1_response_0" type="radio" name="ctl00$cphMainContent$ctl00$iq1$response" value="1">

I want the test to pass when the checked attribute is not present

Answer Source

You can create a method to handle it properly. Note this following is in C#/Java mixed style, you need to tweak a bit to compile.

private boolean isAttribtuePresent(WebElement element, String attribute) {
    Boolean result = false;
    try {
        String value = element.getAttribute(attribute);
        if (value != null){
            result = true;
    } catch (Exception e) {}

    return result;

How you use it:

WebElement input = driver.findElement(By.cssSelector("input[name*='response']"));
Boolean checked = isAttribtuePresent(input, "checked");
// do your asserts
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download