Handling Toggle Buttons in Selenium with Java

By Published · Updated on

To handle a toggle button in Selenium with Java, locate the element, read its current state (isSelected() for checkbox-based toggles, or a class or ARIA attribute for custom toggles), click it, wait for the change, and assert the new state with JUnit. Toggle buttons are common in modern web apps for managing preferences, enabling settings or switching themes, but validating their state changes can be tricky. This guide shows how to automate toggles with Selenium and Java, organise and verify test cases with JUnit testing frameworks, and run tests across browsers in a remote test lab such as LambdaTest.

Handling Toggle Buttons in Selenium with Java

In short:

  1. Locate the toggle with a stable selector (id, name, data-testid, CSS or XPath).
  2. Check the current state before you interact.
  3. Click the toggle, using an explicit wait if needed.
  4. Assert the new state through the DOM, not just the visual look.
  5. Run the same tests across browsers and platforms in a remote grid.

What is a toggle button in a web app?

A toggle button is a UI element that lets users switch between two states, such as "show/hide", "yes/no" or "on/off", with a single tap or click. It is the digital equivalent of a physical switch and offers an intuitive way to change settings.

What are the core functions of a toggle button?

Toggles show a binary state, give instant feedback and are designed for ease of use.

FunctionWhat it means
Binary stateTwo mutually exclusive options; choosing one cancels the other. Shown by a ticked or unticked checkbox, a colour change (e.g. grey for "off", green for "on") or a position shift such as a sliding switch.
Instant feedbackUsers expect the change to apply immediately, without clicking "Apply" or "Save", which suits simple settings like notifications or dark/light mode.
UsabilitySingle action and clear visual cues reduce effort, especially on mobile and responsive designs where space is limited; good toggles also support users with accessibility needs.

When should toggle buttons be used?

Use toggles for simple, immediate on/off choices.

  • Enabling or disabling system options (for example Wi-Fi or sound).
  • Turning settings or features on and off.
  • Switching between modes (such as grid view vs. list view).
  • Showing or hiding components dynamically.

What does the HTML for a toggle switch look like?

A common pattern is a checkbox input wrapped in a label with a styled slider.

<label class="switch">

  <input type="checkbox" id="toggleFeature">

  <span class="slider round"></span>

</label>

How can I automate a toggle button with Selenium WebDriver and Java?

Find the toggle element, check its current state, click it, and verify that the state changed. Here is the step-by-step process.

Step 1: How do you locate the toggle element?

Use any locator strategy: id, name, className, cssSelector or xpath.

WebElement toggle = driver.findElement(By.id("toggleButton"));

If the toggle is custom-built (such as a span or div), CSS selectors or XPath are often the most effective.

Step 2: How do you check the current state?

Use isSelected() for checkbox or radio toggles, and an attribute or class check for custom toggles.

boolean isToggledOn = toggle.isSelected();

For a custom toggle (such as a div whose class changes), use getAttribute() or getCssValue():

String classValue = toggle.getAttribute("class");

boolean isToggledOn = classValue.contains("on");

Note: newer Selenium 4 releases also offer getDomAttribute() and getDomProperty(), which make it explicit whether you read the HTML attribute or the live property.

Step 3: How do you click the toggle?

Call click(), adding an explicit wait if the element may not be ready.

toggle.click();

With a wait condition:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));

wait.until(ExpectedConditions.elementToBeClickable(toggle));

toggle.click();

Step 4: How do you assert the new state?

Use JUnit (or another test framework) to assert the expected behaviour.

Assert.assertTrue(toggle.isSelected());  // If it should now be ON

Or verify via an attribute or class:

String updatedClass = toggle.getAttribute("class");

Assert.assertTrue(updatedClass.contains("on"));

Step 5 (optional): How do you run the test in a remote test lab?

Point a RemoteWebDriver at a cloud Selenium Grid such as LambdaTest to test across platforms and browsers.

DesiredCapabilities caps = new DesiredCapabilities();

caps.setBrowserName("Chrome");

caps.setPlatform(Platform.WINDOWS);

WebDriver driver = new RemoteWebDriver(new URL("https://your-lab-url"), caps);

LambdaTest lets you run Selenium Java tests on an online Selenium Grid, which can reduce test execution time.

How do you run Selenium toggle tests on LambdaTest?

Set your credentials and grid URL, define capabilities, create a RemoteWebDriver, then write the toggle test as normal.

1. How do you configure LambdaTest credentials?

Create a LambdaTest account and copy your username and access key from the dashboard. Keep real keys out of source code, for example by reading them from environment variables.

String accessKey = "your-access-key";

String username = "your-username";

2. How do you set the remote URL?

Build the hub URL from your username and access key.

String gridUrl = "https://" + username + ":" + accessKey + "@hub.lambdatest.com/wd/hub";

3. How do you set the desired capabilities?

Define the operating system, browser, version and test metadata.

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.setCapability("browserName", "Chrome");

capabilities.setCapability("version", "latest");

capabilities.setCapability("platform", "Windows 11");

capabilities.setCapability("name", "Toggle Button Test");

capabilities.setCapability("build", "Selenium Java Toggle Tests");

capabilities.setCapability("selenium_version", "4.8.0"); // or your preferred version

With Selenium 4, the W3C standard names are browserVersion and platformName; LambdaTest's capabilities generator shows the exact format it expects.

4. How do you prepare the RemoteWebDriver?

Pass the grid URL and capabilities to RemoteWebDriver.

WebDriver driver = new RemoteWebDriver(new URL(gridUrl), capabilities);

5. How do you write the toggle test?

Write it exactly as you would locally.

driver.get("https://your-app-url.com");

WebElement toggle = driver.findElement(By.id("toggleButton"));

// Check current state

String toggleClass = toggle.getAttribute("class");

boolean isOn = toggleClass.contains("active");

// Toggle it

toggle.click();

// Recheck state

Thread.sleep(2000); // or use WebDriverWait

String newClass = toggle.getAttribute("class");

Assert.assertTrue(newClass.contains("active"));  // or false if you're toggling off

6. How do you close the session?

Quit the driver after the test.

driver.quit();

This setup lets you run Selenium tests on 3,000+ operating system and browser combinations through LambdaTest's cloud infrastructure, which suits testing toggle behaviour across environments.

How do I combine JUnit with Selenium for toggle button tests?

Add the Selenium and JUnit dependencies, then write a test class with setup, test and teardown methods.

1. Which dependencies do you need?

With Maven, add selenium-java and junit to your pom.xml.

<dependencies>

  <!-- Selenium Java -->

  <dependency>

    <groupId>org.seleniumhq.selenium</groupId>

    <artifactId>selenium-java</artifactId>

    <version>4.8.0</version>

    <scope>test</scope>

  </dependency>

  <!-- JUnit -->

  <dependency>

    <groupId>junit</groupId>

    <artifactId>junit</artifactId>

    <version>4.13.2</version>

    <scope>test</scope>

  </dependency>

</dependencies>

2. How do you write the JUnit test class?

Open the page in @Before, toggle and assert in @Test, and quit the driver in @After.

import org.junit.After;

import org.junit.Assert;

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.chrome.ChromeDriver;

public class ToggleButtonTest {

    private WebDriver driver;

    @Before

    public void setUp() {

        // Path to your local chromedriver (Selenium 4.6+ can also manage the driver automatically)

        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

        driver = new ChromeDriver();

        driver.get("https://your-app-url.com");

    }

    @Test

    public void testToggleButton() {

        WebElement toggle = driver.findElement(By.id("toggleButton"));

        // Check the current toggle state

        boolean isOn = toggle.getAttribute("class").contains("active");

        // Click to toggle

        toggle.click();

        // Optional wait to allow UI change

        try { Thread.sleep(1000); } catch (InterruptedException e) { }

        // Verify toggle state changed

        boolean isNowOn = toggle.getAttribute("class").contains("active");

        Assert.assertNotEquals(isOn, isNowOn);

    }

    @After

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}

What extra tips help?

Use real selectors, explicit waits and RemoteWebDriver for cloud runs.

  • Replace toggleButton with the real selector or ID of your toggle.
  • Use WebDriverWait instead of Thread.sleep() for more robust waits.
  • To run in a remote test lab such as LambdaTest, use RemoteWebDriver instead of ChromeDriver.

What are common problems when testing toggle buttons with Selenium?

Most failures come from unstable locators, weak state checks, timing issues and browser differences.

ProblemCauseSolution
Unstable locatorsInline styles or dynamic classes that change at runtimeUse stable attributes such as id, name or custom data-* attributes
Weak state verificationAssuming the visual state is correct without checking the DOMUse getAttribute() to check aria-checked, classes or the underlying values
Synchronisation and timingState changes after a delay or animationUse explicit waits (WebDriverWait) instead of Thread.sleep()
Cross-browser differencesWhat works in Chrome may break in Safari or Firefox, especially with CSS-centric togglesTest in a remote lab such as LambdaTest across OS and browser combinations
No visible state changeThe toggle changes state without a DOM attribute change or visible confirmationVerify the resulting behaviour (API calls, UI changes, saved settings)
AJAX or JavaScript delaysThe toggle triggers calls that are not immediateWait for specific elements or conditions after the click
Accessibility gapsToggles not usable with screen readers or keyboardAdd accessibility checks or use dedicated accessibility tools
Wrong JUnit assertionsMisused assertions cause false positives or negativesUse suitable assertions (assertEquals, assertTrue, etc.) with correct state extraction

Pro tip: combine JUnit tests with a Selenium Grid in a remote test lab such as LambdaTest to run tests in parallel and catch browser-specific problems early.

What are the best practices for toggle button tests?

Verify the starting state, use stable selectors, test both directions, assert through the DOM, wait explicitly and test across devices, accessibility states and CI runs.

  1. Validate the initial state: always confirm whether the toggle starts OFF or ON before interacting, so you do not flip the wrong switch.
  2. Use stable, unique selectors: prefer IDs, data-testid or stable class names; avoid dynamic classes or brittle XPath that changes with app updates.
  3. Test both transitions: OFF to ON and ON to OFF, verifying the UI updates, API calls or state changes each triggers.
  4. Use assertions intelligently: check DOM properties or local storage values, ARIA attributes (aria-pressed, aria-checked) and CSS classes (for instance .active or .on).
  5. Add waits where needed: use WebDriverWait for the UI to reflect the change before asserting; avoid Thread.sleep() unless essential.
  6. Test on various devices and browsers: use a remote lab such as LambdaTest for desktop and mobile platforms, several browser versions and different screen resolutions.
  7. Test accessibility states: confirm toggles work with the keyboard (Tab, Enter, Space) and with screen readers through correct ARIA roles.
  8. Combine functional and UI tests: check that the underlying function runs (for example notifications turned off or dark mode enabled), not just the visual state.
  9. Include negative tests: test invalid states and disabled (greyed-out) toggles, and confirm toggles cannot be clicked when they should not be.
  10. Run frequently in CI/CD: add toggle tests to your automated regression suite and run them on code check-ins to catch UI state issues early.

Why does this approach matter?

Automating toggles properly gives you reliable, reusable UI test suites. JUnit adds a maintainable test architecture, modular test cases and structured assertions, while a remote test lab such as LambdaTest lets you validate toggle behaviour across browsers and operating systems for real-world accuracy. As apps grow more complex, combining Selenium, JUnit and scalable cloud infrastructure helps teams release stable cross-platform software with confidence.

Frequently asked questions

How do I handle toggle buttons in Selenium if the toggle does not use an <input> tag?

If the toggle is a custom component (such as a <span> or <div>), target it with CSS selectors or XPath and simulate a click. Verify its state through attribute or class changes.

Can we test toggle buttons across different devices and browsers?

Yes. A remote test lab such as LambdaTest lets you run Selenium tests on multiple OS versions, browsers and devices for broader compatibility testing.

How do I check that a toggle triggers the right behaviour in the application?

Besides the toggle's visual state, check dependent element visibility, UI changes or network activity that should change as a result of the toggle action.

Can I run toggle button tests in headless mode?

Yes. ChromeDriver supports headless execution, which is useful for running automated UI tests in CI pipelines or on servers without a graphical interface.

Why should I use a remote test lab for toggle button tests?

Remote test labs give access to real platforms and browsers, so you can confirm that toggle functionality behaves reliably across diverse environments.

TECHNOLOGY

Written by
· 268 articles
Business, technology and finance writer