How To Automate Toggle Buttons In Selenium Java
Fidaa Berrjeb
Posted On: November 24, 2022
200991 Views
13 Min Read
If you pay close attention, you’ll notice that toggle switches are all around us because lots of things have two simple states: either ON or OFF (in binary 1 or 0).
From light switches to turning on airplane mode when you want to rest and receiving no calls to the preferences page on our favorite mobile app, we interact with toggles daily.
Toggle buttons, just like checkboxes, dropdowns, or radio buttons, are classic UI components that most of us know and love.
You can also watch this video to learn how to select multiple checkboxes in Selenium WebDriver Java. If you are preparing for an interview you can learn more through Selenium interview questions.
They can usually be found on settings pages for an overall system or application.
While performing automated browser testing, there’ll be plenty of times when you’d have to handle the toggle buttons. Often used in applications, as we mentioned, they are best used to change the state of system features and preferences. Toggles can replace two radio buttons or one checkbox to allow users to choose between opposing states. This simple UI component can greatly impact the user experience using a web or mobile application. Thereby, it becomes vital that while testing websites, we also know how to handle toggle buttons.
In all such applications and services, web developers and QA engineers face challenges writing automated test cases to handle toggle buttons.
In this Selenium Java tutorial, we’ll look at how to automate toggle buttons in Selenium Java.
So, let’s get started!
TABLE OF CONTENTS
Use cases of Toggle Buttons
In this section of this tutorial on how to automate toggle buttons in Selenium Java, we will review the three best use cases for using toggle switches in web and mobile applications.
Dark Mode
According to Grapecity, 70% of developers prefer dark mode IDE while coding or programming. That means 7 out of 10 programmers use dark light modes over birth ones.
If you plan on implementing it on your site, you’ll need to use a toggle switch.
Airplane mode
Airplane mode gives you a quick way to turn off all wireless communications on your device. For example – When turning airplane mode on for iOS, Apple provides immediate results by changing the cellular bars in the upper left-hand corner to an airplane icon.
Cookies management
Disabling cookies in your browser is generally a good idea for protecting (and increasing) your privacy. Cookie Switch ON|OFF helps you quickly turn cookies (browser cookies) in your browser ON or OFF with just one button.
Sample Toggle Button in HTML:
When used in web development, a toggle switch is not a native element, so developers have devised ways to mimic this element using HTML and CSS.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<ul class="tg-list"> <li class="tg-list-item"> <h4>Light</h4> <input class="tgl tgl-light" id="cb1" type="checkbox"> <label class="tgl-btn" for="cb1"></label> </li> <li class="tg-list-item"> <h4>iOS</h4> <input class="tgl tgl-ios" id="cb2" type="checkbox"> <label class="tgl-btn" for="cb2"></label> </li> <li class="tg-list-item"> <h4>Skewed</h4> <input class="tgl tgl-skewed" id="cb3" type="checkbox"> <label class="tgl-btn" data-tg-off="OFF" data-tg-on="ON" for="cb3"></label> </li> <li class="tg-list-item"> <h4>Flat</h4> <input class="tgl tgl-flat" id="cb4" type="checkbox"> <label class="tgl-btn" for="cb4"></label> </li> <li class="tg-list-item"> <h4>Flip</h4> <input class="tgl tgl-flip" id="cb5" type="checkbox"> <label class="tgl-btn" data-tg-off="Nope" data-tg-on="Yeah!" for="cb5"></label> </li> </ul> |
How to handle toggle buttons in Selenium?
The Selenium framework is a set of different tools, but the most popular and useful to new and experienced testers is Selenium WebDriver. Selenium WebDriver is a free and open-source tool that allows you to interact with a website for web automation testing. It also supports popular programming languages like Java, JavaScript, Python, C#, Ruby, and PHP.
With the help of Selenium WebDriver, it is possible to request clicking of the browser’s back and front buttons. This feature is not available in many automation testing tools, which is the biggest advantage of using Selenium as an automation testing tool.
Selenium is my preferred and one of the best test automation frameworks I use to write automated tests. When writing this blog on how to automate toggle buttons in Selenium Java, the latest Selenium version available is Selenium 4. So from my experience using Selenium 4 for months since it launched in October 2021, I’ll mention some advantages of this latest version of Selenium framework:
Usage of WebDriver Manager
In the Selenium 4 release, there is no need to download the latest executable for an individual browser. We can write a single-line code to download the latest version for the specified driver.
Relative Locators
Introduction of relative locators in Selenium 4 helps locate web elements based on the visual location relative to other DOM elements, an easy way of locating. This means testers can now locate specific web elements using intuitive terms often used by users like toLeftOf, toRightOf, Above, Below, etc.
newWindow
This allows users to create and switch to a new window/tab without creating a new WebDriver object.
Renewed Selenium Grid
The Grid in Selenium 4 also has an enhanced user-friendly GUI. The new Selenium Grid comes with Docker support. So managing Selenium Grid is now smooth and easy as there will no longer be any need to set up and start hubs and nodes separately.
Selenium Grid allows you to run test cases on different machines across different platforms. The control of triggering the test cases is on the local end, and when the test cases are triggered, they are automatically executed by the remote end.
After developing the WebDriver tests, you may need to run your tests on multiple browsers and operating system combinations. This is where Grid comes into the picture.
Run your Selenium Java test scripts across 3000+ browser environments. Try LambdaTest Now!
Demonstration: How to Automate toggle buttons in Selenium Java?
For demonstrating toggle buttons, I have used the CodePen, which houses the code with five toggle buttons link.
We would be executing the test on the LambdaTest cloud grid. Cloud testing tools like LambdaTest allow you to perform cross browser testing at scale over an online browser farm of 3000+ browser versions and operating systems. With LambdaTest, you can also automate Selenium Java tests in parallel over an online Selenium Grid, thus reducing the test execution time.
You can also subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorial around automated browser testing, Cypress E2E testing, End to End testing, and more.
A sample automation test script using Selenium with Java in a LambdaTest grid looks like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
import org.openqa.selenium.WebDriver; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.*; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.*; import java.net.MalformedURLException; import java.net.URL; import java.time.Duration; import java.util.HashMap; public class ToggleButtonLambdaTest { WebDriver driver = null; public static String status = "passed"; String gridURL = "@hub.LambdaTest.com/wd/hub"; String user_name = System.getenv("LT_USERNAME") == null ? "LT_USERNAME" : System.getenv("LT_USERNAME"); String access_key = System.getenv("LT_ACCESS_KEY") == null ? "LT_ACCESS_KEY" : System.getenv("LT_ACCESS_KEY"); String testURL = "https://codepen.io/fidabrj/pen/NWYeaqG"; private static final int MAX_COUNT = 6; String build_name; @BeforeTest @Parameters(value={"browser","version","platform", "resolution"}) public void testSetUp(String browser, String version, String platform, String resolution) throws Exception { DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); desiredCapabilities.setCapability("browserName", browser); desiredCapabilities.setCapability("browserVersion", version); HashMap<String, Object> ltOptions = new HashMap<String, Object>(); ltOptions.put("username", user_name); ltOptions.put("accessKey", access_key); ltOptions.put("platformName", platform); ltOptions.put("resolution", resolution); ltOptions.put("project", "Demonstration: Toggle Button on LambdaTest Grid"); build_name = "Toggle - " + browser + " on " + platform + " combination"; ltOptions.put("build", build_name); desiredCapabilities.setCapability("LT:Options", ltOptions); try { driver = new RemoteWebDriver(new URL("https://" + user_name + ":" + access_key + gridURL), desiredCapabilities); } catch(MalformedURLException exc) { exc.printStackTrace(); } } @Test(description="Demonstration of Toggle Buttons on LambdaTest Selenium Grid") public void test_toggle_buttons() throws InterruptedException { WebElement result_frame; WebElement toggle_button; String cssSelectorString; /* Keep a count of the buttons present on the page */ Integer count = 1; driver.get(testURL); Thread.sleep(2000); /* Selenium Java 3.141.59 */ WebDriverWait wait = new WebDriverWait(driver, 5); /* WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); */ try { /* Switch to the iFrame using the ID locator */ result_frame = driver.findElement(By.id("result")); driver.switchTo().frame(result_frame); /* Now that we are inside the iFrame, toggle all the buttons present in the iFrame */ for (count = 1; count < MAX_COUNT; count++) { Thread.sleep(2000); cssSelectorString = "[for='cb" + count + "']"; toggle_button = driver.findElement(By.cssSelector(cssSelectorString)); toggle_button.click(); } } catch (Exception e) { System.out.println(e.getMessage()); status = "failed"; } } @AfterTest public void tearDown() { if (driver != null) { ((JavascriptExecutor) driver).executeScript("lambda-status=" + status); driver.quit(); } } } |
Code Walkthrough
Step 1:
The code starts by creating an instance of Selenium Remote WebDriver as it will be used to execute the code on the Selenium cloud grid.
1 2 3 4 5 6 7 8 9 10 |
WebDriver driver = null; try { driver = new RemoteWebDriver(new URL("https://" + user_name + ":" + access_key + gridURL), desiredCapabilities); } catch(MalformedURLException exc) { exc.printStackTrace(); } |
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 automate toggle buttons in Selenium Java, the LambdaTest platform has been used.
Follow the demonstration to set the environment variables:
- Go to the LambdaTest Dashboard.
- From the left menu, click on Builds under the Automation section.
- Click on the key icon from the top-right corner of your screen and copy the Access Key and Username.
Alternatively, you can set the environment variables via your LambdaTest Profile
- From the LambdaTest Dashboard, click on the Profile icon in the top-right corner of your screen, then click on Profile.
- You will find your Username & Access Key.
1 2 3 4 5 6 |
public static String status = "passed"; String gridURL = "@hub.LambdaTest.com/wd/hub"; String user_name = System.getenv("LT_USERNAME") == null ? "LT_USERNAME" : System.getenv("LT_USERNAME"); String access_key = System.getenv("LT_ACCESS_KEY") == null ? "LT_ACCESS_KEY" : System.getenv("LT_ACCESS_KEY"); |
Step 3:
We need to update our test capabilities in the test script. This code passes browser, browser version, and operating system information along with LambdaTest Selenium grid capabilities via the capabilities object. By Adding the first function in this file testSetUp() 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.
Step 4:
After setting initial capabilities, we start our test case by Switching to the iFrame using the ID locator. Below are the two methods to identify if our code uses an iFrame or not:
- Right-click on the page. If you find “view frame source,” the response is yes; it’s an iFrame.
- Simply inspect the element and search with the keyword “iframe.”
The challenge we may face in handling iFrames in Selenium is that Selenium WebDriver cannot directly access and locate web elements inside iFrames in Selenium. Selenium can only access elements in a specific context, and the context of the main web page and the embedded iFrame are different. Selenium explicitly needs to switch context to access elements inside the iFrame.
Selenium first needs to switch the context to the iFrame to access all the web elements inside the iframe. And as we know, Selenium WebDriver provides three ways to switch the focus to a specific iframe:
- Using the Index of the iframe.
- Using the Name or Id of the iframe.
- Using the Web Element object of the iframe.
Selenium WebDriver provides the switchTo().frame() method to switch the execution context to the identified iframe.
In this blog on how to automate toggle buttons in Selenium Java, we switched to the iFrame using the ID of the Frame:
1 2 |
result_frame = driver.findElement(By.id("result")); driver.switchTo().frame(result_frame); |
Step 5:
Now that we are inside the iFrame, toggle all the buttons present in the iFrame.
1 2 3 4 5 6 |
for (count = 1; count < MAX_COUNT; count++) { Thread.sleep(2000); cssSelectorString = "[for='cb" + count + "']"; toggle_button = driver.findElement(By.cssSelector(cssSelectorString)); toggle_button.click(); |
Step 6:
Once the test is completed, we must close the browser after each run. That is why we add another function tearDown(), to close the browser and annotate it with @AfterTest annotation to ensure execution after every test case.
1 2 3 4 5 6 7 |
public void tearDown() { if (driver != null) { ((JavascriptExecutor) driver).executeScript("lambda-status=" + status); driver.quit(); } |
Test Execution
So far, in this blog on how to automate toggle buttons in Selenium Java, we have covered and understood the various ways to locate, interact and implement the code for toggle button automation. We will execute the code in the local and LambdaTest platform step by step.
Since the project created is a TestNG project, we execute the test cases as TestNG runs and observe the output below as shown on the local and LambdaTest dashboard, where we can see the details of test execution.
We will limit our demonstration to showing LambdaTest Dashboard execution. By running the test from your IDE, the browser will not open locally this time. Connect to your LambdaTest account, and go to LambdaTest Dashboard. You will see under Automation > Build that your test is running:
As it’s a simple test, it will finish fast. You can see the recording of the test execution, and I find this very helpful as I can identify quickly in case the test fails the reason and in which step exactly. To do so, click on the tab as shown in the screenshot.
You can also use the right-hand panel to navigate to a specific step and see what happened there:
Do you want to advance your Selenium with Java skills? LambdaTest offers the Selenium Java 101 certification that helps you get a comprehensive understanding of what you need to achieve mastery of automation testing using Selenium with Java.
Conclusion
In this tutorial blog on how to automate toggle buttons in Selenium Java, we have learned about toggle buttons and implementation on the web page and how we can interact with them while performing automated UI testing.
And as a bonus, you could also see how to parallelize the tests and run them on the remote Selenium grid to save the test execution time.
Frequently Asked Questions (FAQs)
How does Java handle toggle buttons in selenium?
Java handles toggle buttons in Selenium the same way HTML and JavaScript do. The value of the button is a boolean, true or false. If it is true, the button is turned on, and clicking it will turn it off. If it is false, it is turned off, and clicking it will turn it on.
How do you automate buttons in Selenium?
There are several ways to automate buttons in Selenium. The simplest one is using locators like name and text. For example, if you have a button with the id “myButton,” you can click it using the following code:
1 |
driver.findElement(By.id("myButton")).click(); |
However, sometimes we don’t know the button’s ID, and we need to find another way. In this case, we can use a method called “FindElements.” This method will return all the elements that match the given CSS selector.
Got Questions? Drop them on LambdaTest Community. Visit now