Checking a checkbox with WebDriver

For something as simple as checking a checkbox you would think that all the different browser drivers would implement this in the same way. But sadly this is not the case. Firefox expects that you click on a checkbox to check or uncheck it whereas both the IEDriver and ChromeDriver expect you to type a space to do the same. This is all well and good for running a simple once off test, but we cant be expected to change code and re-build every time we want to test in a different browser.

Thankfully there is a solution at hand. Once we know which browser is currently running the test, we can decide which method to use. I have provided a C# and a Java code snippet below:

C#

IWebElement checkbox = driver.FindElement(By.Id("ElementID"));

if (((RemoteWebDriver)driver).Capabilities.BrowserName == "firefox")
{
    // Firefox
    checkbox.Click();
}
else
{
    // Chrome and IE
    checkbox.SendKeys(Keys.Space);
}

Java

WebElement checkbox = driver.findElement(By.id("idOfTheElement");

if (driver.Capabilities.BrowserName.Equals("firefox"))
{
    checkbox.Click();
}
else
{
    checkbox.SendKeys(Keys.Space);
}

If you come across any other discrepancies between the different driver implementations let us know in the comments.

Advertisements

One thought on “Checking a checkbox with WebDriver

  1. John Randolff February 11, 2015 / 3:09 pm

    Wow I cant believe that they would have different implementations like that. Imho both actions should be available for checkboxes in all of the driver implementations.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s