How To Select Multiple Checkboxes in Selenium WebDriver Using Java
In this article, readers will use a tutorial to learn various techniques on how to select multiple Checkboxes in Selenium WebDriver using Java, including code.
Join the DZone community and get the full member experience.
Join For FreeHave 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 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 select multiple Checkboxes in Selenium WebDriver using Java.
What Is a Checkbox?
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.
Note: 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 the 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.
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"));
Using the Class Name
The 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"));
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;
}
}
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 “pre” and “post” validation as it helps to verify the state of the Checkbox before and after the click operation is performed.
Demonstration
So far, we have looked at the different ways to locate, select, and validate Checkboxes. In this section, 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 two files:
BaseClass
TestCheckboxes
BaseClass.java
will have the code for browser initialization and connecting to the Remote Selenium Grid.TestCheckboxes.java
will have two test cases explaining all the ways to locate, select, and perform validations on multiple Checkboxes in Selenium WebDriver.
Let’s get started now:
Step 1
Create a Maven project in Eclipse and name it as MultipleCheckboxes
.
Note: 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.
Step 2
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>
Step 3
Add two 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 to 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 the 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 article, the LambdaTest platform has been used:
String username = "<lambdatest_username>";
String accessKey = "<lambdatest_accesskey>";
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");
}
}
Step 4
Once the test is completed, we also need to close the browser after each run, which is why we add another function, closeDriver()
, to close the browser and annotate it with the @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 two test cases:
- Test case 1: Demonstration of the interaction with a single Checkbox.
- Test case 2: Demonstration of the interaction with multiple Checkboxes by traversing through them.
Both of 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 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
In the first test case, testSingleCheckbox
, we fetch the checkbox element using its ID locator:
WebElement checkbox = driver.findElement(By.id("isAgeSelected"));
Step 3
After this, pre-validation is applied to verify if the given Checkbox is displayed or not. 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 4
After checking the Checkbox, post-validation is applied to verify the Checkbox is checked:
if(checkbox.isSelected())
{
System.out.println("Checkbox is checked");
}
Step 5
Moving to the second test case: testMultipleCheckbox
, 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 6
The 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 7
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 8
After checking all of them, the next code is to deselect the Checkbox at index 1 from the list and 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.
Test Execution
So far in this article, 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 the local where we can see the details of execution.
Test Case 1: testSingleCheckbox
Test Case 2: testMultipleCheckbox
Conclusion
We have now wrapped up this article 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 article also explains the pre and post validations while working with Checkboxes in Selenium WebDriver and executing the same on the cloud Selenium Grid 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!
Published at DZone with permission of Vipul Gupta. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments