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.