Thursday, February 10, 2011

The Checkbox Quandary

So since I haven't posted in a month, and couldn't think of anything better to discuss, I'm going to share a neat little solution to what I call "The checkbox quandary".  It is summarized as follows:

Clicking on a checkbox only changes it's state.  Selenium doesn't know how to set it to a specific state.  This means that the value of the checkbox could potentially fluctuate each time we run our test.  To get around this we typically check the state of the checkbox before we check it.  Doing this each time is a pain, so here is a simple setCheckbox routine that does the logic for you. It takes standard locator and a boolean specifying if you want the checkbox checked or not.

 public void setCheckbox(string locator, bool isChecked)
        {
            selenium.waitForVisible(locator);
            if((isChecked==true)!=(selenium.IsChecked(locator)))
            {
                    click(locator);
            }

        }

The logic is pretty simple.  If our checkbox state isn't the specified state, we click the checkbox.  Otherwise, it's already in the correct state so we do nothing.  We put a waitForVisible command in there to make sure the element is fully rendered (and all javascript routines on the page are loaded) before we click on it.

3 comments:

  1. What's wrong with the Selenium Check(locator) and Uncheck(locator) methods? They work just like you'd expect.

    ReplyDelete
  2. hi:

    It´s posible tried in Selenium ide??

    I´ve problem recording test with checkbox, but i can´t know if is marked or not.

    Thanks

    ReplyDelete
  3. SEO agency in Abu Dhabi

    http://www.districtmarketing.ae

    District Marketing is best service provider company in abu dhabi. If you have increase your website ranking then you can join seo agency. To know more you can visit our official website.@ http://www.districtmarketing.ae/

    best seo agency in abu dhabi
    seo agency in abu dhabi
    seo agency in abu dhabi
    best seo agency in abu dhabi

    ReplyDelete