How To Select Multiple Checkboxes In Selenium Using Java?
Have you ever wondered how frustrating it would be if you had to log in each time you wanted to view your Facebook profile? Or in a multiple-choice question where you’d like to mark many options but can’t? Or do you have to enter your card information each time you make a payment since you can’t save it?
These are only a few of the numerous instances on web pages where quick functionality might be useful. Stay logged in for a while, save card details, and much more with a simple click. Basically, it’s a technique to turn things on and off while also allowing for multi-selection.
The answer to this in the world of web development is Checkboxes. Checkboxes have a wide implementation in web pages and help users give consent/toggle or select multiple choices as required in various applications.
With their increased usage, as an automation engineer, it is expected that you know how to handle Checkboxes using test automation frameworks like Selenium.
In this Selenium Java tutorial, we will discuss various techniques on how to automate and how to select multiple Checkboxes in Selenium WebDriver using Java.
A Checkbox is a GUI element on any webpage that facilitates users to make choices from the given set of options. Once the choice is made, it helps record it for further processing.
The Checkbox can allow the user to make:
A single choice from the list of options
Multiple choices from the list of options
Give consent (or toggle on/off) for certain requirements on a webpage
In the implementation, a Checkbox is said to have two states:
When it is selected, it is termed as Checked
When it is deselected, it is termed as UnChecked
It is interesting to note that some applications also provide an intermediate state also called a tri-state where instead of a tick mark, which is the usual representation of a checked Checkbox, a filled box or a dash is used to dedicate the selection. This happens in cases where we have parent-child Checkboxes, and a child Checkbox is selected that makes an auto-selection for all the parent Checkboxes in the hierarchy.
Checkboxes in Web pages
Checkboxes are majorly used on web pages to offer multiple choices to a user. On an HTML page, these can be identified with several unique properties that can be used to automate Checkboxes using Selenium WebDriver.
A Checkbox in DOM is defined using the input tag with type as Checkbox like the following:
<input type="checkbox">
Due to this implementation, all web element locator strategies can be used to locate and automate the Checkbox in Selenium WebDriver.
How to locate multiple Checkboxes in Selenium WebDriver?
Before we jump to how to select multiple Checkboxes in Selenium WebDriver using Java and the implementation part of Checkboxes in automation, it would be good to understand different ways to locate it in a webpage and how we can select the Checkbox once it is located.
Locating Checkboxes using the ID attribute
While using the ID locator in Selenium, in most well-designed web pages, an id value is allocated to all the HTML tags. So if the Checkbox under interaction has an id associated with it, then we can use that unique value to interact with the Checkbox.
As for the Checkbox here, the id value is assigned. So it can be located as follows:
WebElement checkbox = driver.findElement(By.id("isAgeSelected"));
Locating Checkboxes using the Class Name
className locator in Selenium can be used when there is a group of Checkboxes, and each of them needs to be interacted with since the elements of the same group would fall under the same class name.
Hence, the Checkboxes located by this means are stored in a List of WebElements and can be interacted with using the index from the list.
As seen in the above example, all Checkboxes are in the same group. Hence, they have the same Class Name.
They can be located as shown below:
List<WebElement> checkboxes = driver.findElements(By.className("cb-element mr-10"));
Locating Checkboxes using the element Value
Checkboxes can be located using their Value attribute as Checkbox has a unique value assigned to it. This strategy is mostly used in cases when Checkboxes are in a group. Due to this, they would all have the same Class or Name attribute linked to them, along with having a unique Value that aids in interacting with a particular Checkbox.
This is one example where the Class is the same for all the different Values. We can use the Value attributes for all the Checkboxes to identify them uniquely.
List<WebElement> checkboxes = driver.findElements(By.xPath("//input[@name='color']"));
for(int i=0; i<checkboxes.size(); i++)
{
String value = checkboxes.get(i).getAttribute("value");
if (value.equalsIgnoreCase("orange"))
{
//perform action on checkbox which have value as orange
break;
}
}
Locating Checkboxes using CSS Selector or XPath
At times, it is not easy to locate an element on the web page directly using its attributes. The same is the case with Checkboxes. Sometimes, the implementation in DOM is not feasible to select them using unique identifiers, or even value attributes like we previously discussed.
In such cases, using a CSS selector or XPath Selector to locate the Checkboxes becomes the most ideal way:
//locating a checkbox using XPath
WebElement checkbox = driver.findElement(By.xpath("//input[@id='isAgeSelected']"));
//locating a checkbox using CSS Selector
WebElement checkbox = driver.findElement(By.cssSelector("input[id='isAgeSelected']"));
We have deep-dived into the different ways to locate a Checkbox. In the next section, we will learn how to select multiple Checkboxes in Selenium WebDriver using Java.
How to select multiple Checkboxes in Selenium WebDriver using Java?
Let’s look into the mechanisms through which you can interact with the checkbox.
A Checkbox in Selenium WebDriver can be selected/checked or deselected/unchecked by simply clicking on it using the click() method of the Selenium WebDriver.
Once a Checkbox is located, we simply click on it to change its state.
WebElement checkbox = driver.findElement(By.id("isAgeSelected"));
checkbox.click();
If a Checkbox is in an unchecked state, then the click would transition it to a checked state and vice-versa.
Performing validations on Checkboxes using Selenium WebDriver
By validating Checkboxes, we mean to validate the state of a Checkbox before and after the Click() operation is performed on the Checkbox. For this, Selenium WebDriver provides few functions that can be used while working with multiple Checkboxes.
The isSelected() method is used to validate the current state of a Checkbox, irrespective of whether it is selected or not. Along similar lines, before clicking, we might need to check if the Checkbox is not only displayed but also enabled for interaction. The isEnabled() and isDisplayed() methods in Selenium are respectively used for checking if the checkboxes are displayed and enabled on the webpage.
An important thing to note here is that methods isDisplayed() and isEnabled() fall under pre-validation as they are used before clicking on the Checkbox. The isSelected() method falls under both pre and post validation as it helps to verify the state of the Checkbox before and after the click operation is performed.
Demonstration: Automating Multiple Checkboxes in Selenium WebDriver using Java
So far, we have looked at the different ways to locate, select and validate Checkboxes. In this section of this article on how to select multiple Checkboxes in Selenium WebDriver using Java, let us look at how Selenium WebDriver methods can be used for automating interactions with the Checkboxes on the page. I will be using Selenium Java bindings for the demo. A few things to note about the automation testing example before we start are:
We will be creating a Maven project using Java in Eclipse IDE.
It will use Selenium WebDriver for web automation and TestNG for test case execution.
The project would consist of 2 files: BaseClass and TestCheckboxes.
BaseClass.java will have the code for browser initialization and connecting to the Remote Selenium Grid.
TestCheckboxes.java will have 2 test cases explaining all the ways to locate, select and perform validations on multiple Checkboxes in Selenium WebDriver.
Let’s get started now…
Create a Maven project in Eclipse and name it as MultipleCheckboxes. Those who are not a fan of Eclipse can follow the same steps in the IDE of their choice. The setup and results would still be the same.
Update the pom.xml file of your project to have Selenium and TestNG dependencies. We will be using the latest version for both of these.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>MultipleCheckboxes</groupId> <artifactId>MultipleCheckboxes</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <release>16</release> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.Seleniumhq.Selenium</groupId> <artifactId>Selenium-java</artifactId> <version>4.1.4</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.5</version> <scope>test</scope> </dependency> </dependencies> </project>
Add 2 Java class files inside your src/test package and name them as BaseClass.java and TestCheckboxes.java.
Code Walkthrough: BaseClass
Inside the BaseClass file, add the following code for browser session initialization to run the test cases and close it after the case is completed.
package test;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.Selenium.remote.DesiredCapabilities;
import org.openqa.Selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class BaseClass {
public RemoteWebDriver driver = null;
String username = "<lambdaTest_username>";
String accessKey = "<lambdaTest_accesskey>";
@BeforeMethod
public void setUp() {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "Chrome");
capabilities.setCapability("version", "92.0");
capabilities.setCapability("platform", "Windows 10");
capabilities.setCapability("resolution", "1024x768");
capabilities.setCapability("build", "Multiple Checkboxes using Selenium JAVA");
capabilities.setCapability("name", "Multiple Checkboxes using Selenium JAVA");
try {
driver = new RemoteWebDriver(
new URL("https://" + username + ":" + accessKey
+ "@hub.lambdatest.com/wd/hub"), capabilities);
} catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
}
}
@AfterMethod
public void closeDriver() {
driver.quit();
}
}
This will be inherited to our test class, thus preventing redundancy for such code to create WebDriver sessions and launch the browser on the grid. It also provides an abstraction of driver code from every other class user.
Step 1. In this file, we start by creating an instance of Selenium Remote WebDriver as it will be used to execute the code on Selenium Cloud Grid.
public RemoteWebDriver driver = null;
Executing on Selenium Grid cloud helps execute multiple cases together in parallel across a variety of browsers and OS. It also offers speed and scalability, making executions faster and more reliable.
Step 2. As mentioned in the previous step, since we are using a cloud grid, we would need to add the credentials of the cloud platform used to execute our code. In this blog on how to select multiple Checkboxes in Selenium WebDriver using Java, the LambdaTest platform has been used.
String username = "<lambdatest_username>";
String accessKey = "<lambdatest_accesskey>";
LambdaTest facilitates cross browser testing over an online browser farm of 3000+ real browsers and operating systems on the cloud and also provides interactive dashboards to analyze the run reports and logs as required.
To fetch your username and access key, visit the Profile Section on your Dashboard after creating your profile on LambdaTest.
Step 3. Add the first function in this file setUp() to set the initial capabilities for the browser and make the connection with the LambdaTest remote grid.
This function is annotated with the @BeforeMethod
annotation in TestNG, as we would want to execute this function before every test run.
@BeforeMethod
public void setUp() {
//code to set the DesiredCapabilites as needed for the browser
//Selenium Capabillities Generator of LambdaTest can be used for this
try {
driver = new RemoteWebDriver(
new URL("https://" + username + ":" + accessKey
+ "@hub.lambdatest.com/wd/hub"), capabilities);
} catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
}
}
Another advantage of using the LambdaTest platform can be seen here with the use of Selenium Desired Capabilities Generator to perform Selenium TestNG testing on the LambdaTest platform with your desired browsers and operating systems combinations by selecting them as required.
Step 4. Once the test is completed, we also need to close the browser after each run, and that is why we add another function closeDriver() to close the browser and annotate it with @AfterMethod
annotation to ensure execution after every test case.
@AfterMethod
public void closeDriver() {
driver.quit();
}
Code Walkthrough: TestCheckboxes
Inside this TestCheckboxes.java file, we will add 2 test cases:
TestCase 1: Demonstration of interaction with a single Checkbox.
TestCase 2: Demonstration of interaction with multiple Checkboxes by traversing through them.
Both these cases will also have Checkbox validation methods.
package test;
import java.util.List;
import org.openqa.Selenium.By;
import org.openqa.Selenium.WebElement;
import org.testng.annotations.Test;
public class TestCheckboxes extends BaseClass{
@Test
public void testSingleCheckbox()
{
System.out.println("Navigating to the URL");
driver.get("https://www.lambdatest.com/Selenium-playground/checkbox-demo");
//using ID attribute to locate checkbox
WebElement checkbox = driver.findElement(By.id("isAgeSelected"));
//pre-validation to confirm that checkbox is displayed.
if(checkbox.isDisplayed())
{
System.out.println("Checkbox is displayed. Clicking on it now");
checkbox.click();
}
//post-validation to confirm that checkbox is selected.
if(checkbox.isSelected())
{
System.out.println("Checkbox is checked");
}
}
@Test
public void testMultipleCheckbox()
{
System.out.println("Navigating to the URL");
driver.get("https://www.lambdatest.com/Selenium-playground/checkbox-demo");
//using class name to fetch the group of multiple checkboxes
List<WebElement> checkboxes = driver.findElements(By.className("cb-element mr-10"));
//traverse through the list and select all checkboxes if they are enabled and displayed.
for(int i=0; i<checkboxes.size(); i++)
{
if(checkboxes.get(i).isDisplayed() && checkboxes.get(i).isEnabled())
{
System.out.println("Checkbox is displayed at index : " + i + " Clicking on it now");
checkboxes.get(i).click();
}
}
//deselect the checkbox on index 1 from the list of checkboxes selected above
System.out.println("de-selecting checkbox with index 1");
checkboxes.get(1).click();
if(checkboxes.get(1).isSelected())
{
System.out.println("Checkbox is still selected");
}
else
{
System.out.println("Checkbox is deselected successfully");
}
}
}
Step 1. As you can see, both the test cases in this file have the common code to launch the browser and navigate to the webpage under test for which the below code is used.
System.out.println("Navigating to the URL");
driver.get("https://www.lambdatest.com/Selenium-playground/checkbox-demo");
Step 2-a. In the first test case testSingleCheckbox, we fetch the checkbox element using its ID locator.
WebElement checkbox = driver.findElement(By.id("isAgeSelected"));
Step 2-b. After this, pre-validation is applied to verify if the given Checkbox is displayed or not, and on the basis of that, it is selected using the click() method.
if(checkbox.isDisplayed())
{
System.out.println("Checkbox is displayed. Clicking on it now");
checkbox.click();
}
Step 2-c. After checking the Checkbox, post-validation is applied to verify that the Checkbox is checked.
if(checkbox.isSelected())
{
System.out.println("Checkbox is checked");
}
Step 3-a. Now moving to the second test case testMultipleCheckbox, in this one, we have implemented the logic to traverse through a group of Checkboxes having the same class name to identify and interact with them along with pre and post validations.
Step 3-b. First step in this case would be to fetch the list of Checkbox web elements using the same class name and then store that into a variable of a List type.
List<WebElement> checkboxes = driver.findElements(By.className("cb-element mr-10"));
Step 3-c. Next we use the for loop to traverse through the Checkboxes list and select all of them one by one after verifying that Checkbox is displayed and enabled to interact with.
for(int i=0; i<checkboxes.size(); i++)
{
if(checkboxes.get(i).isDisplayed() && checkboxes.get(i).isEnabled())
{
checkboxes.get(i).click();
}
}
Step 3-d. After checking all of them, the next code is to deselect the Checkbox at index 1 from the list and then do a post validation to validate if it is unchecked after the click or not.
checkboxes.get(1).click();
if(checkboxes.get(1).isSelected())
{
System.out.println("Checkbox is still selected");
}
else
{
System.out.println("Checkbox is deselected successfully");
}
With this, we have understood the entire code and implementation for the test class. Let’s continue to see the execution results on the local and the LambdaTest dashboard.
Test Execution
So far in this blog on how to select multiple checkboxes in Selenium WebDriver using Java, we have covered and understood the various ways to locate, interact and implement the code for Checkboxes automation. Now we move forward to execute the code as discussed in previous sections.
Since the project created is a TestNG project, we execute the cases as TestNG runs and observe the output would be like below on local and LambdaTest dashboard where we can see the details of execution.
For test case 1: testSingleCheckbox
More detailed logs and step-by-step command execution can be seen on the LambdaTest dashboard by navigating to the test.
For test case 2: testMultipleCheckbox
To use advanced tools for analyzing the performance of your tests, go to the LambdaTest Analytics Dashboard. You can see all test results, their status, and the overall number of tests passed or failed in the Test Summary area. In addition, you may see snapshots of recently executed test runs in the Test Overview section.
Conclusion
We have now wrapped up the blog on how to select multiple Checkboxes in Selenium WebDriver using Java. In this, we have learned about different Checkbox locator strategies on the basis of implementation on the web page and how we can interact with them while performing automated UI testing.
This blog also explains the pre and post validations while working with Checkboxes in Selenium WebDriver and executing the same on the cloud Selenium Grid like LambdaTest while performing Selenium automation testing.
By now, you should be confident enough to work with multiple Checkboxes in your project. So go ahead and start checking some Checkboxes.
Happy Checking!!