Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed assets/images/selenium/java1.png
Binary file not shown.
Binary file removed assets/images/selenium/java2.png
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
281 changes: 66 additions & 215 deletions docs/java-frameworks.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
id: java-framework
title: Execute Selenium Tests With Java
title: Run your Selenium Java tests on LambdaTest
sidebar_label: Java
description: Your guide to running tests using Java on LambdaTest's Selenium Grid of 3000+ real devices and desktop browsers.
keywords:
Expand Down Expand Up @@ -44,250 +44,101 @@ import TabItem from '@theme/TabItem';
})
}}
></script>

# Selenium With Java Tutorial

---

In this topic, you will learn how to configure and run tests using **Java** on LambdaTest's [Selenium testing cloud platform](https://www.lambdatest.com/selenium-automation).

## Objectives

---

By the end of this topic, you will be able to:

1. Set up an environment for testing your hosted web pages using **Java** with Selenium.
2. Specify which browsers to perform **Java** automation testing on.
3. Test your locally hosted pages on LambdaTest platform.
4. Explore advanced features of LambdaTest.
This guide walks you through the process of running Selenium Java tests on LambdaTest, a cloud-based cross-browser testing platform. By following these steps, you can seamlessly execute automated tests on a wide range of browsers and operating systems using LambdaTest’s Selenium Grid.

## Prerequisites
Before you begin, ensure you have the following:

---

Before you can start performing Java automation testing with Selenium, you would need to:

- Install the latest **Java development environment**. We recommend to use **Java 11** version.

- Download the latest **Selenium Client** and its **WebDriver bindings** from [the official website](https://www.selenium.dev/downloads/). Latest versions of **Selenium Client** and **WebDriver** are ideal for running your automation script on LambdaTest Selenium cloud grid.

- Setup your environment with required Selenium bindings if you are using an IDE for running the tests. These are the steps required to configure your IDE :

- **Step 1:** Download the latest Java Selenium Bindings from the [official website](https://www.selenium.dev/downloads/) and extract the **ZIP** file to your project directory.
- **Step 2:** Create a new Java project and once it's created, you can open the project settings. Here we are showing an example for the same in **IntelliJ IDEA CE**.
<img loading="lazy" src={require('../assets/images/selenium/java1.png').default} alt="cmd" width="1260" height="1071" className="doc_img"/>

- **Step 3:** Navigate to **dependencies** in module settings where you can add your external JARs.
- **Step 4:** Under dependencies by clicking the **`+`** icon, you can add your downloaded **Selenium JARs** to the project. Once they are added, it should look like this :
<img loading="lazy" src={require('../assets/images/selenium/java2.png').default} alt="cmd" width="1150" height="740" className="doc_img"/>

Now you are good to run the Java automation testing scripts.

## Run Your First Test
- Your [LambdaTest Username and Access Key](https://accounts.lambdatest.com/)
- Install Java Development Kit (JDK). We recommend Java version 11
- Install [Maven](https://maven.apache.org/)
- [Download](https://www.selenium.dev/downloads/) the latest Selenium Client and its WebDriver bindings

---

Let’s start with a simple Selenium Remote WebDriver test first. The Java script below tests a simple to-do application with basic functionalities like mark items as done, add items in a list, calculate total pending items etc.
## Step 1: Configure your test suite

### Sample Test with Java
:::tip Sample repo
Download or Clone the code sample for the Java from the LambdaTest GitHub repository to run the tests on our Standard Grid.

```java title="JavaToDo.java"
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class JavaTodo {
String username = "YOUR_LAMBDATEST_USERNAME";
String accesskey = "YOUR_LAMBDATEST_ACCESS_KEY";
static RemoteWebDriver driver = null;
String gridURL = "@hub.lambdatest.com/wd/hub";
boolean status = false;
public static void main(String[] args) {
new JavaTodo().test();
}
public void test() {
// To Setup driver
setUp();
try {
//Change it to production page
driver.get("https://lambdatest.github.io/sample-todo-app/");
<a href="https://github.com/LambdaTest/java-selenium-sample" className="github__anchor" target="_blank"><img loading="lazy" src={require('../assets/images/icons/github.png').default} alt="Image" className="doc_img"/> View on GitHub</a>
:::

//Let's mark done first two items in the list.
driver.findElement(By.name("li1")).click();
driver.findElement(By.name("li2")).click();
```bash
git clone https://github.com/LambdaTest/java-selenium-sample.git
cd java-selenium-sample
```

// Let's add an item in the list.
driver.findElement(By.id("sampletodotext")).sendKeys("Yey, Let's add it to list");
driver.findElement(By.id("addbutton")).click();
If you are using your own project, make sure you update the **Hub endpoint** in your tests file. By setting up the Hub endpoint, you establish the communication channel between your tests and the browser nodes, enabling effective test distribution and execution.

// Let's check that the item we added is added in the list.
String enteredText = driver.findElementByXPath("/html/body/div/div/div/ul/li[6]/span").getText();
if (enteredText.equals("Yey, Let's add it to list")) {
status = true;
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
tearDown();
}
}
private void setUp() {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("version", "70.0");
capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get any available one.
capabilities.setCapability("build", "LambdaTestSampleApp");
capabilities.setCapability("name", "LambdaTestJavaSample");
try {
driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
} catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private void tearDown() {
if (driver != null) {
((JavascriptExecutor) driver).executeScript("lambda-status=" + status);
driver.quit(); //really important statement for preventing your test execution from a timeout.
}
}
```java title="Test.java"
// highlight-next-line
public static String hubURL = "https://hub.lambdatest.com/wd/hub";
private WebDriver driver;
public void setup() throws MalformedURLException {
//... your capabilities
// highlight-next-line
driver = new RemoteWebDriver(new URL(hubURL), capabilities);
}
```

**Step 1:** Once you setup your environment with the latest Java Selenium bindings, create a new java file `<file_name>.java` in your current project or testing directory and add the above code snippet.
## Step 2: Update the dependencies
Run the command below to check for outdated dependencies. Review updates carefully before modifying your `pom.xml`, as they might not be compatible with your code.

### Setting up your Authentication

Make sure you have your LambdaTest credentials with you to run test automation scripts on LambdaTest Selenium Grid. You can obtain these credentials from the [LambdaTest Automation Dashboard](https://automation.lambdatest.com/build) or through [LambdaTest Profile](https://accounts.lambdatest.com/login).

**Step 2:** Please edit and add your **UserName** and **AccessKey** which are generated from the platform in your `<file_name>.java` file:

<div className="lambdatest__codeblock">
<CodeBlock className="language-java">
{`String username= "${ YOUR_LAMBDATEST_USERNAME()}";
String accesskey= "${ YOUR_LAMBDATEST_ACCESS_KEY()}";`}
</CodeBlock>
</div>
```bash
mvn versions:display-dependency-updates
```

### Configuring your Test Capabilities
## Step 3: Configure your test Capabilities
LambdaTest requires specific capabilities to set the browser, browser version, operating system, and other configurations for your test.

**Step 3:** In this code, we are passing browser, browser version, and operating system information, along with LambdaTest Selenium grid capabilities via capabilities object. The capabilities object in the above code is defined as:
Example desired capabilities for testing on Chrome 120:

```java
```java title="Test.java"
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("version", "70.0");
capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
capabilities.setCapability("build", "LambdaTestSampleApp");
capabilities.setCapability("name", "LambdaTestJavaSample");
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("version", "120.0");
capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
capabilities.setCapability("build", "LambdaTestSeleniumSampleApp");
capabilities.setCapability("name", "LambdaTestJavaSample");
```

:::info Note

:::tip
You can generate capabilities for your test requirements with the help of our inbuilt :link: **[Capabilities Generator tool](https://www.lambdatest.com/capabilities-generator/)**.

:::

### Executing the Test

- If you are using an editor or IDE for running your tests, you can just build and run your configured java file in your editor/IDE.
- If you are using a terminal/cmd, you would need to execute the following commands :

```bash
cd to/file/location
#Compile the test file:
javac -classpath ".:/path/to/selenium/jarfile:" <file_name>.java
#Run the test:
java -classpath ".:/path/to/selenium/jarfile:" <file_name>
```

**Example:**

```bash
cd /Users/macuser/Documents/LambdaTest_Java
javac -classpath ".:/Users/macuser/Documents/LambdaTest_Java/selenium-server-4.1.1.jar:" JavaTodo.java
java -classpath ".:/Users/macuser/Documents/LambdaTest_Java/selenium-server-4.1.1.jar:" JavaTodo
```

:::info

Your test results would be displayed on the test console (or command-line interface if you are using terminal/cmd) and on [LambdaTest automation dashboard](https://automation.lambdatest.com/build). LambdaTest Automation Dashboard will help you view all your text logs, screenshots and video recording for your entire automation tests.

:::

## Testing Locally Hosted or Privately Hosted Projects

---

You can test your locally hosted or privately hosted projects with [LambdaTest Selenium grid cloud](https://www.lambdatest.com/selenium-automation) using LambdaTest Tunnel app. All you would have to do is set up an SSH tunnel using LambdaTest Tunnel app and pass toggle `tunnel = True` via desired capabilities. LambdaTest Tunnel establishes a secure SSH protocol based tunnel that allows you in testing your locally hosted or privately hosted pages, even before they are made live.

:::tip Tunnel Help

Refer our :link: [LambdaTest Tunnel documentation](https://www.lambdatest.com/support/docs/testing-locally-hosted-pages/) for more information.

:::

Here’s how you can establish LambdaTest Tunnel.

:::info Download the binary file

- [LambdaTest Tunnel for Windows](https://downloads.lambdatest.com/tunnel/v3/windows/64bit/LT_Windows.zip)
- [LambdaTest Tunnel for Mac](https://downloads.lambdatest.com/tunnel/v3/mac/64bit/LT_Mac.zip)
- [LambdaTest Tunnel for Linux](https://downloads.lambdatest.com/tunnel/v3/linux/64bit/LT_Linux.zip)

:::

Open command prompt and navigate to the binary folder.

Run the following command:

```bash
./LT -user {user’s login email} -key {user’s access key}
```

So if your user name is **lambdatest@example.com**, the command would be:
## Step 4: Setup your LambdaTest credentials
In your terminal (as per your respective Operating System), run these command to setup your LambdaTest credentials.
> You can see your credentials below if you have logged into our platform.

<div className="lambdatest__codeblock">
<Tabs className="docs__val">
<TabItem value="bash" label="Linux / MacOS" default>
<div className="lambdatest__codeblock">
<CodeBlock className="language-bash">
{`./LT -user lambdatest@example.com -key ${ YOUR_LAMBDATEST_ACCESS_KEY()}`}
{`export LT_USERNAME="${ YOUR_LAMBDATEST_USERNAME()}"
export LT_ACCESS_KEY="${ YOUR_LAMBDATEST_ACCESS_KEY()}"`}
</CodeBlock>
</div>
</TabItem>

Once you are able to connect **LambdaTest Tunnel** successfully, you would just have to pass on tunnel capabilities in the code as shown:
<TabItem value="powershell" label="Windows" default>
<div className="lambdatest__codeblock">
<CodeBlock className="language-powershell">
{`set LT_USERNAME="${ YOUR_LAMBDATEST_USERNAME()}"
set LT_ACCESS_KEY="${ YOUR_LAMBDATEST_ACCESS_KEY()}"`}
</CodeBlock>
</div>
</TabItem>
</Tabs>

```java title="Tunnel Capability"
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("tunnel", true);
## Step 5: Execute your test
Replace the `TEST_FILE_NAME` in the below command with your desired test file to execute that particular test on LambdaTest Grid:
```bash
mvn clean install exec:java -Dexec.mainClass="com.lambdatest.TEST_FILE_NAME" -Dexec.classpathScope=test -e
```

## Additional Links

---
Visit the [LambdaTest Web Automation](https://automation.lambdatest.com/build) page to check the status of your test execution.
<img loading="lazy" src={require('../assets/images/selenium/language-frameworks/java/1.png').default} alt="Image" className="doc_img"/>

## Additional Links
- [Advanced Configuration for Capabilities](https://www.lambdatest.com/support/docs/selenium-automation-capabilities/)
- [How to test locally hosted apps](https://www.lambdatest.com/support/docs/testing-locally-hosted-pages/)
- [How to integrate LambdaTest with CI/CD](https://www.lambdatest.com/support/docs/integrations-with-ci-cd-tools/)

<nav aria-label="breadcrumbs">
<ul className="breadcrumbs">
<li className="breadcrumbs__item">
<a className="breadcrumbs__link" target="_self" href="https://www.lambdatest.com">
Home
</a>
</li>
<li className="breadcrumbs__item">
<a className="breadcrumbs__link" target="_self" href="https://www.lambdatest.com/support/docs/">
Support
</a>
</li>
<li className="breadcrumbs__item breadcrumbs__item--active">
<span className="breadcrumbs__link">
Java Automation Testing
</span>
</li>
</ul>
</nav>
- [How to integrate LambdaTest with CI/CD](https://www.lambdatest.com/support/docs/integrations-with-ci-cd-tools/)
2 changes: 1 addition & 1 deletion docs/lambdatest-running-your-first-selenium-test.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ LambdaTest provides a powerful Selenium Grid that allows you to perform automate
## Prerequisites
Before you begin, ensure you have the following:

- Your [LambdaTest Username and Access Key](https://accounts.lambdatest.com/security)
- Your [LambdaTest Username and Access Key](https://accounts.lambdatest.com/)
- Install Java Development Kit (JDK). We recommend Java version 11
- Install [Maven](https://maven.apache.org/)
- [Download](https://www.selenium.dev/downloads/) the latest Selenium Client and its WebDriver bindings
Expand Down
Loading