For AI agents and LLMs: a machine-readable index is available at llms.txt. A plain-Markdown version of any documentation page is available by appending .md to its URL.
Skip to main content

How to Run Selenium Tests With Java on TestMu AI


To run Selenium tests with Java on TestMu AI, set LT_USERNAME and LT_ACCESS_KEY as environment variables, point a RemoteWebDriver at https://hub.lambdatest.com/wd/hub, and pass your browser, version, and OS in LT:Options. Then run your suite with Maven as usual. The browsers run on the TestMu AI cloud grid, and each test's video, logs, and result appear on the Automation Dashboard.

Hosts such as hub.lambdatest.com keep their original names and work as shown.

You can run on 10,000+ browser and OS combinations, and the setup is the same for every framework: you connect to the grid, pass your capabilities, and run. This guide walks through that shared flow once, then gives you a per-framework quickstart for TestNG, JUnit, Cucumber, Selenide, Gauge, Geb, Serenity, and Tesbo, plus a zero-code Java SDK option.

Prerequisites​


Before running any framework below, set up a TestMu AI account, your credentials, the JDK, and Maven.

  1. Create a TestMu AI account if you don't have one.
  2. Get your Username and Access Key from the TestMu AI Dashboard.
  3. Install the Java Development Kit (JDK) 11 or later.
  4. Install Apache Maven. The framework sample projects below all build with Maven.

Set Up Manually Without Maven (Optional)​

If you prefer to run raw Selenium Java without a build tool, add the Selenium JARs to your IDE instead of using Maven.

  1. Download the latest Selenium Java Client and extract the ZIP file to your project directory.
  2. Add the Selenium JARs to your project dependencies in your IDE.
IntelliJ project settings

Navigate to Dependencies in module settings, click +, and add the downloaded Selenium JARs.

Selenium JARs added to project dependencies

With the JARs added, compile and run the test directly from the terminal:

Verified
cd to/file/location
javac -classpath ".:/path/to/selenium/jarfile:" JavaTodo.java
java -classpath ".:/path/to/selenium/jarfile:" JavaTodo

Set Your Credentials​


Every framework authenticates the same way: your Username and Access Key are passed in the grid URL. Set them as environment variables so you don't hard-code them. Pick your operating system:

Verified
export LT_USERNAME="YOUR_LAMBDATEST_USERNAME"
export LT_ACCESS_KEY="YOUR_LAMBDATEST_ACCESS_KEY"

The TestNG and JUnit sample projects read these two variables with System.getenv, so no credentials live in the test code.

How the Sample Test Works​


All the framework repos below run the same sample test, so you only need to understand it once. The test opens the to-do app, marks the first two items done, adds a new item, and verifies it appears:

Verified
driver.get("https://lambdatest.github.io/sample-todo-app/");
driver.findElement(By.name("li1")).click();
driver.findElement(By.name("li2")).click();
driver.findElement(By.id("sampletodotext")).sendKeys("Yey, Let's add it to list");
driver.findElement(By.id("addbutton")).click();

The driver is a RemoteWebDriver pointed at the grid. It reads your credentials from the environment variables you set above and passes your browser/OS choices through LT:Options:

Verified
String username = System.getenv("LT_USERNAME");
String accesskey = System.getenv("LT_ACCESS_KEY");

ChromeOptions browserOptions = new ChromeOptions();
browserOptions.setPlatformName("Windows 10");
browserOptions.setBrowserVersion("latest");

HashMap<String, Object> ltOptions = new HashMap<String, Object>();
ltOptions.put("build", "Java Selenium Build");
ltOptions.put("name", "Java Selenium Test");
ltOptions.put("w3c", true);
browserOptions.setCapability("LT:Options", ltOptions);

driver = new RemoteWebDriver(
new URL("https://" + username + ":" + accesskey + "@hub.lambdatest.com/wd/hub"),
browserOptions);
tip

Use the Capabilities Generator to build an LT:Options block for any browser, version, and OS combination.

What changes between frameworks is only how that test is structured and run: the runner, its setup/teardown hooks, and any config files. That's what each tab below covers.

Run a Test in Your Framework​


Each tab lists just the framework-specific pieces. Clone the matching repo (it contains the full, ready-to-run project), then run the command shown.

TestNG is the most common choice. Each test class creates the driver in @BeforeMethod, then reports its status and quits in @AfterMethod. A suite file (single.xml or parallel.xml) picks which classes run.

  1. Clone the sample GitHub project:
Verified
git clone https://github.com/LambdaTest/Java-TestNG-Selenium
cd Java-TestNG-Selenium
  1. Set your browser and OS in the test class. Each class in src/test/java/com/lambdatest/ reads LT_USERNAME and LT_ACCESS_KEY and sets its own LT:Options. This excerpt from TestNGTodo2.java runs Chrome on Windows 10:
TestNGTodo2.java (excerpt)
String username = System.getenv("LT_USERNAME") == null ? "Your LT Username" : System.getenv("LT_USERNAME");
String authkey = System.getenv("LT_ACCESS_KEY") == null ? "Your LT AccessKey" : System.getenv("LT_ACCESS_KEY");
String hub = "@hub.lambdatest.com/wd/hub";

MutableCapabilities ltOptions = new MutableCapabilities();
ltOptions.setCapability("build", "TestNG With Java");
ltOptions.setCapability("name", m.getName() + this.getClass().getName());
ltOptions.setCapability("platformName", "Windows 10");

ChromeOptions browserOptions = new ChromeOptions();
browserOptions.setCapability("browserVersion", "latest");
browserOptions.setCapability("LT:Options", ltOptions);

driver = new RemoteWebDriver(new URL("https://" + username + ":" + authkey + hub), browserOptions);
  1. parallel.xml runs the three test classes at the same time:
parallel.xml
<suite thread-count="20" parallel="tests" name="Suite">
<test thread-count="20" parallel="classes" name="Test">
<classes>
<class name="com.lambdatest.TestNGTodo1"/>
<class name="com.lambdatest.TestNGTodo2"/>
<class name="com.lambdatest.TestNGTodo3"/>
</classes>
</test>
</suite>
  1. Run a single test, or the parallel suite:
Verified
mvn test -D suite=single.xml
mvn test -D suite=parallel.xml

The test then appears on the Automation Dashboard. A green status confirms it passed.

Run Selenium Tests With Java SDK​


The Java SDK is the zero-code option: it runs your existing TestNG tests on the grid unchanged, injecting credentials and capabilities from a YAML file via a Java agent. Use this when you already have a local suite and don't want to edit test code. See the SDK reference project on GitHub and the full Selenium Java SDK guide.

  1. Add the SDK dependency and agent to your pom.xml (the agent is attached to Surefire via -javaagent):
Verified
pom.xml (key additions)
<dependency>
<groupId>io.github.lambdatest</groupId>
<artifactId>lambdatest-selenium-java-sdk</artifactId>
<version>1.0.1</version>
</dependency>
<!-- plus the maven-dependency-plugin (copies lambdatest-agent.jar) and
maven-surefire-plugin with -javaagent:.../lambdatest-agent.jar -->
  1. Create lambdatest.yml with your credentials, platforms, and features. The SDK loads it automatically and reads ${LT_USERNAME} and ${LT_ACCESS_KEY} from the environment variables you set earlier:
Verified
lambdatest.yml
username: ${LT_USERNAME}
accesskey: ${LT_ACCESS_KEY}

platforms:
- browserName: Chrome
browserVersion: latest
platformName: Windows 10

build: SDK Build v1
name: SDK Test
video: true
tunnel: true
  1. Register the SDK's TestNG listener in testng.xml, then run. Your existing test classes execute as-is:
Verified
mvn test -D suite=testng.xml

The test then appears on the Automation Dashboard. A green status confirms it passed.

Common Capabilities​


Set the W3C capabilities (browserName, browserVersion, platformName) on the browser options object, and TestMu AI capabilities inside LT:Options. These are the ones Java suites set most often. The full list, with defaults and aliases, is in Selenium automation capabilities.

CapabilitySet onExampleWhat it does
browserNameBrowser optionsChromeBrowser to run. Case sensitive. ChromeOptions, FirefoxOptions and SafariOptions set it for you.
browserVersionBrowser optionslatest, latest-1Browser version. Defaults to latest.
platformNameBrowser options or LT:OptionsWindows 10, macOS SonomaOperating system. Case sensitive. If you leave it out, TestMu AI picks one that suits the browser.
buildLT:OptionsJava Selenium BuildGroups tests into one build on the dashboard. Keep it under 255 characters.
nameLT:OptionsJava Selenium TestTest name shown on the dashboard.
tagsLT:Options{"Staging", "Sanity"}Labels for grouping and filtering tests.
resolutionLT:Options1920x1080Screen resolution of the VM. Defaults to 1024x768.
videoLT:OptionstrueRecords a video of the test. On by default.
visualLT:OptionstrueCaptures a screenshot at each step. Off by default; adds run time.
networkLT:OptionstrueRecords network logs. Off by default; adds run time.
consoleLT:OptionstrueRecords browser console (JavaScript) logs. Off by default.
tunnelLT:OptionstrueRoutes traffic through TestMu AI Tunnel so the browser can reach local or private pages. Off by default.
tunnelNameLT:Optionsmy-java-tunnelPicks which running tunnel to use.

In Java, add them to the same ltOptions map:

ltOptions.put("resolution", "1920x1080");
ltOptions.put("network", true);
ltOptions.put("console", true);
ltOptions.put("tags", new String[] { "Staging", "Sanity" });

View Your Results​


Open the TestMu AI Automation Dashboard after mvn test finishes. Each run shows as a build named by your build capability, with one entry per test named by name. Open a test to see its video and command-by-command execution, plus network logs, console logs, and step screenshots if you turned them on.

To mark a test passed or failed, send the lambda-status Lambda Hook before you quit the driver. The TestNG sample does this in @AfterMethod:

((JavascriptExecutor) driver).executeScript("lambda-status=passed");

Supported values are passed, failed, skipped, ignored, unknown, and error.

Test Locally Hosted Pages With TestMu AI Tunnel​


If the site under test runs on localhost, a staging server, or a private network, start TestMu AI Tunnel on your machine and tell the test to use it.

  1. Download the Tunnel binary for your OS and start it with your credentials and a tunnel name. Step-by-step setup is in the guides for macOS, Windows, and Linux.
LT --user YOUR_LAMBDATEST_USERNAME --key YOUR_LAMBDATEST_ACCESS_KEY --tunnelName my-java-tunnel
  1. Add the tunnel capabilities to LT:Options, using the same tunnel name:
ltOptions.put("tunnel", true);
ltOptions.put("tunnelName", "my-java-tunnel");
  1. Run your tests as usual. If a browser refuses a plain localhost URL, open localhost.lambdatest.com or your machine's IP address instead.

For flags, proxies, and other options, see TestMu AI Tunnel and testing locally hosted pages.

Run in CI​


In CI, store your username and access key as secrets and expose them as LT_USERNAME and LT_ACCESS_KEY. The test code doesn't change. A GitHub Actions job for the TestNG sample:

.github/workflows/selenium-java.yml
name: selenium-java
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "17"
- name: Run TestNG suite on TestMu AI
env:
LT_USERNAME: ${{ secrets.LT_USERNAME }}
LT_ACCESS_KEY: ${{ secrets.LT_ACCESS_KEY }}
run: mvn test -D suite=parallel.xml

In Jenkins, bind your credentials to the same two environment variables and run the same Maven command. See Jenkins with TestMu AI and the other CI/CD integrations.

Troubleshooting​


Match the message your test prints. The full list is in common Selenium errors.

ErrorCauseFix
Authentication error when the session startsLT_USERNAME or LT_ACCESS_KEY is missing or wrong in the shell that runs Maven. The TestNG and JUnit samples then send the placeholder Your LT Username.Run echo $LT_USERNAME in the same terminal. Copy both values again from the key icon on the Automation Dashboard. In CI, check the secret names.
SessionNotCreatedException: Could not start a new sessionThe browser, driver, Selenium client, or JDK versions don't match.Check that the browser version and your Selenium and JDK versions are compatible. Build the capabilities with the Capabilities Generator.
Lambda Error: Uh Oh! Looks like our Grid failed to recognize your test input.A capability has the wrong data type (a string where an integer is expected), or no VM was free during a traffic spike.Check each capability's type in Selenium automation capabilities, then retry.
Exceeded Queue LimitMore tests started than your plan's concurrency allows, and the runner closed the connection while they waited in the queue.Lower thread-count in parallel.xml to your concurrency limit, and raise your client's connection timeout.
Max Duration ExceededThe test ran longer than the maximum duration (1800 seconds by default), often because of an endless loop.Split it into smaller tests, check for loops, or set the maxDuration capability.
localhost refused to connectSome browsers don't accept localhost as the URL through the tunnel.Open localhost.lambdatest.com or your machine's IP address instead.
The test can't reach a local or staging siteThe tunnel isn't running, or tunnelName doesn't match the name you started it with.Start the tunnel first and use the same name in tunnelName. See Tunnel troubleshooting.

Frequently Asked Questions​


Can I run Selenium Java tests online without a local Selenium setup?​

Yes. You write and compile the test on your machine with the JDK and Maven, and RemoteWebDriver sends each command to the TestMu AI grid, where the browser runs. You don't install browsers, drivers, or a Selenium Grid locally. TestMu AI is not an online Java compiler: your build still runs where you start it, on your machine or in CI.

How do I run TestNG tests with Selenium on TestMu AI?​

Clone Java-TestNG-Selenium, export LT_USERNAME and LT_ACCESS_KEY, and run mvn test -D suite=single.xml. The TestNG tab above has each step.

How do I run TestNG test cases in parallel?​

Run mvn test -D suite=parallel.xml. Its <test> element sets parallel="classes" and thread-count="20", so all three sample classes start at once. Tests above your plan's concurrency limit wait in a queue until a slot frees up.

Is JUnit set up the same way?​

Yes. JUnit uses the same RemoteWebDriver, grid URL, and LT:Options. Only the lifecycle annotations (@Before and @After) and the runner differ. The JUnit tab above runs mvn test -P single or mvn test -P parallel.

How do I keep my username and access key out of the code?​

Set them as the LT_USERNAME and LT_ACCESS_KEY environment variables and read them with System.getenv("LT_USERNAME"). In CI, store them as secrets and map them to the same names. The Java SDK reads ${LT_USERNAME} and ${LT_ACCESS_KEY} in lambdatest.yml.

Next Steps​


Continue with these related guides:

To see what else the grid offers, read about Selenium automation on TestMu AI.

Help and Support

Related Articles