How To check Checkboxes checked or not in Selenium Java, Python, C#

Yosuva ArulanthuC#, Java, Python, Selenium, Test Automation, TestingLeave a Comment

Checkboxes are an often used element in web applications. But how do you work with them in your Selenium tests? Intuitively you may reach for a method that has the word ‘checked’ in it — like .checked? or .isChecked. But this doesn’t exist in Selenium. So how do you do it?

Solution

There are two ways to approach this — by seeing if an element has a checked attribute (a.k.a. performing an attribute lookup), or by asking an element if it has been selected.

Let’s check multiple examples here

Example

Java

// filename: Checkboxes.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.List;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

public class Checkboxes {
    WebDriver driver;

    @Before
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
    }

    @Test
    public void checkboxDiscoveryTest() {
        driver.get("http://the-internet.herokuapp.com/checkboxes");
        List<WebElement> checkboxes = driver.findElements(By.cssSelector("input[type='checkbox']"));

        System.out.println("With .attribute('checked')");
        for (WebElement checkbox : checkboxes) {
            System.out.println(String.valueOf(checkbox.getAttribute("checked")));
        }

        System.out.println("\nWith .selected?");
        for (WebElement checkbox : checkboxes) {
            System.out.println(checkbox.isSelected());
        }
    }

    @Test
    public void checkboxOption1Test() throws Exception {
        driver.get("http://the-internet.herokuapp.com/checkboxes");
        WebElement checkbox = driver.findElement(By.cssSelector("form input:nth-of-type(2)"));
        assertThat(checkbox.getAttribute("checked"), is(not("null")));
        assertThat(checkbox.getAttribute("checked"), is("true"));
    }

    @Test
    public void checkboxOption2Test() throws Exception {
        driver.get("http://the-internet.herokuapp.com/checkboxes");
        WebElement checkbox = driver.findElement(By.cssSelector("form input:nth-of-type(2)"));
        assertThat(checkbox.isSelected(), is(true));
    }

}

Python

# filename: checkboxes.py
import unittest
from selenium import webdriver


class Checkboxes(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def tearDown(self):
        self.driver.quit()

    def test_list_values_for_different_approaches(self):
        driver = self.driver
        driver.get('http://the-internet.herokuapp.com/checkboxes')
        checkboxes = driver.find_elements_by_css_selector('input[type="checkbox"]')

        print("With .get_attribute('checked')")
        for checkbox in checkboxes:
            print(checkbox.get_attribute('checked'))

        print("\nWith .is_selected")
        for checkbox in checkboxes:
            print(checkbox.is_selected())
    def test_list_values_for_different_approaches(self):
        # ...
        assert checkboxes[-1].get_attribute('checked')
        # or
        assert checkboxes[-1].is_selected()
    def test_list_values_for_different_approaches(self):
        # ...
        assert checkboxes[0].get_attribute('checked')
        # or
        assert checkboxes[0].is_selected()

if __name__ == "__main__":
    unittest.main()

Ruby

#need to add code

C#

// filename: Checkboxes.cs
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;

public class Checkboxes
{
    IWebDriver Driver;

    [SetUp]
    public void SetUp()
    {
        Driver = new FirefoxDriver();
    }

    [TearDown]
    public void TearDown()
    {
        Driver.Quit();
    }
    [Test]
    public void CheckboxDiscovery()
    {
        Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/checkboxes");
        IReadOnlyCollection<IWebElement> Checkboxes = Driver.FindElements(By.CssSelector("input[type=quot;checkboxquot;]"));

        Console.Write("With .attribute('checked')");
        foreach(IWebElement Checkbox in Checkboxes)
        {
            Console.WriteLine(Checkbox.GetAttribute("checked"));
        }

        Console.WriteLine("With .selected?");
        foreach(IWebElement Checkbox in Checkboxes)
        {
            Console.WriteLine(Checkbox.Selected);
        }
    }
    [Test]
    public void GetCheckBoxStatusByAttribute()
    {
        Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/checkboxes");
        IWebElement Checkbox = Driver.FindElement(By.CssSelector("form input:nth-of-type(2)"));
        Assert.That(Checkbox.GetAttribute("checked").Equals("true"));
    }
    [Test]
    public void GetCheckBoxesStatusByQuery()
    {
        Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/checkboxes");
        IWebElement Checkbox = Driver.FindElement(By.CssSelector("form input:nth-of-type(2)"));
        Assert.That(Checkbox.Selected);
    }
}

When you save and run the file here is what will happen:

  • Open the browser
  • Visit the page
  • Find all of the checkboxes on the page
  • Assert that the second checkbox (the one that is supposed to be checked on the initial page load) is checked
  • Close the browser

Leave a Reply

Your email address will not be published.