Skip to main content

Run your first Selenium 4 test

Your guide to running Selenium 4 tests with Java on BrowserStack.

Introduction

BrowserStack gives you instant access to our Selenium Grid of 2000+ real devices and desktop browsers. This guide gives step-by-step information to successfully run your first test using Selenium 4 with Java on BrowserStack.

Note: Currently, the sample test script is available only in Java. We plan to add test scripts for other languages soon.

Prerequisites

  • A BrowserStack account set up: If you haven’t created an account yet, sign up for a free trial or purchase a plan.
  • Access to your BrowserStack credentials: Go to the Automate Dashboard and note your Username and Access key.
  • Setup with the required Selenium 4 client language bindings: If you already have a setup that runs Selenium 4 tests, then you can skip this step. If not, follow these steps in few of the most commonly used Java development environments:
  1. Open the Eclipse IDE and create a new JAVA project.
  2. Download the Selenium 4 Java bindings and extract the ZIP file to your Eclipse project directory.
  3. Right-click the project name and click Build Path -> Configure Build Path.

    Selenium Java Bindings for Eclipse Configure Build Path
  4. Select Classpath.

    Select Classpath from the list
  5. Click Add External JARs and add the Selenium Java bindings (a .jar file) and all the dependent libraries (.jar files in the /libs folder) that you extracted in the second step. The Classpath lists all the libraries added as shown in the following image:

    Add the Selenium Java bindings extracted in first step

Your Eclipse setup is now ready for the first Selenium 4 test to be run on BrowserStack.

  1. Download the Selenium 4 Java bindings and extract the ZIP file to your Eclipse project directory.
  2. Open the IntelliJ IDEA IDE and create a new JAVA project.
  3. Go to File -> Project Structure.
  4. Click Modules > Dependencies in the Project Structure window as shown below:

    IntelliJ IDEA Configuration
  5. Click (+) as shown above, and then click JARs or directories to select the Selenium Java bindings (a .jar file) and all the dependent libraries (.jar files in the /libs folder) as extracted in the first step.

The Project Structure window lists all the libraries added as shown in the following image:

IntelliJ IDEA Project Structure

Your IDE setup is now ready to be able to run Selenium tests on BrowserStack.

If you are using any other IDE apart from Eclipse, IntelliJ, or maven, use the following steps:

  1. Download the Selenium 4 Java bindings and extract the ZIP file to your Eclipse project directory.
  2. Open your IDE and create a new JAVA project.
  3. Find the option to add classpath for adding external JARs as dependencies.
  4. Add the Selenium Java bindings (a .jar file) and all the dependent libraries (.jar files in the /libs folder) as extracted from the ZIP in first step.

The setup is now ready to run Selenium 4 tests.

If you are using Maven to build your project, add the following dependency in your pom.xmlfile to use Selenium 4 in your project:

<dependency>
   <groupId>org.seleniumhq.selenium</groupId>
   <artifactId>selenium-java</artifactId>
   <version>4.0.0</version>
</dependency>

Run your first test

As part of this guide, we will run a Selenium 4 test that does the following:

  1. Opens google.com.
  2. Enters a search string BrowserStack in the browser.
  3. Clicks the I’m Feeling Lucky button.
  4. Asserts the page URL.
  5. Marks the status of the test as either passed or failed based on the assertion.

Step 1 - Select the OS-device-browser combination

Use the capability builder to select the OS-device-browser combination that you want the test to run on.

Based on your selection, replace the capabilities given in the sample test script with the combination that you selected.

Step 2 - Understand the sample test script

Use the sample Java test script that we provide to run your first Selenium 4 test on BrowserStack. This test script uses the relative locators and the updated Action class features of Selenium 4.

Relative locators let you locate any complex UI elements in a fewer lines of code. In situations where UI elements might be relative to a key UI element, relative locators make accessing these relative elements easier. The available relative locators in Selenium 4 are above, below, toLeftOf, toRightOf, and near. This test script uses the toRightOf locator to locate the I’m Feeling Lucky button on the Google Search page.

Some other use cases for relative locators are:

  • For e-commerce websites, relative lcoators can help identify a unique button if there exist multiple buttons with the same name on a single page.
  • UI elements that do not include unique IDs
  • UI elements that are identified with complex CSS or XPath expression

Action class is used to simulate actions from a keyboard or mouse on a specific element. In Selenium 4, the syntax of the Action class has changed. Check out the modifications to the Action class to learn more. This test script uses the moveToElement(onElement).click() method to simulate the click action of your mouse.

Apart from these features that are used in the test script, you can also try out other CDP features that Selenium 4 introduces and we support. Check out the Event-driven Testing features for more information.

Important: If you want to use the CDP features on BrowserStack, you must use the seleniumCdp capability and set it to true.

Step 3 - Write the sample test script

In your Java project, create a new file JavaSample.java and copy the following code to this file:

Note: Currently, the sample test script is available only in Java. We plan to add test scripts for other languages soon.
// Sample test in Java to run Automate session.
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.locators.RelativeLocator.with;

public class JavaSample {
  public static String REMOTE_URL = "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub";
//  public static String REMOTE_URL = "http://localhost:4444/wd/hub";

  public static void main(String[] args) throws MalformedURLException {
    DesiredCapabilities capabilities = new DesiredCapabilities();

    // Setting the browser capability
    capabilities.setCapability("browserName", "chrome");
      
    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();

    // Setting the OS or device version capabilities
    browserstackOptions.put("os", "Windows");
    browserstackOptions.put("osVersion", "10");
    
    // Setting a build name for the test
    browserstackOptions.put("buildName", "BStack-[Java] Selenium 4 Sample Test"); 
      
    // Setting a session name for the test    
    browserstackOptions.put("sessionName", "Selenium 4 test");

    // Setting the Selenium version
    browserstackOptions.put("seleniumVersion", "4.0.0");
    capabilities.setCapability("bstack:options", browserstackOptions);

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

    try {
      driver.get("https://www.google.com");
      WebElement searchField = driver.findElement(By.name("q"));
      searchField.sendKeys("BrowserStack");
      WebElement searchButton = driver.findElement(By.name("btnK"));

      // Using relative locators of Selenium 4 to locate a button
      WebElement feelingLucky = driver.findElement(with(By.name("btnI")).toRightOf(searchButton));

      // Using Action class of Selenium 4
      Actions actions = new Actions(driver);
      actions.moveToElement(feelingLucky).click().build().perform();
        
      // Setting the status of test as 'passed' or 'failed' based on the condition; if URL of the web page contains 'browserstack'
      WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
      try {
        wait.until(ExpectedConditions.urlContains("browserstack"));
        markTestStatus("passed","URL contains 'browserstack'!",driver);
      }
      catch(Exception e) {
        markTestStatus("failed","URL does not contain 'browserstack'",driver);
      }
      System.out.println(driver.getCurrentUrl());
      driver.quit();
    } catch (Exception e) {
      markTestStatus("failed", "Exception!", driver);
      e.printStackTrace();
      driver.quit();
    }
  }

  // marking the tests as passed or failed in BrowserStack
  public static void markTestStatus(String status, String reason, WebDriver driver) {
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");
  }
}

Warning: Ensure that you include the driver.quit() statement at the end of the test script to avoid timeout issues. If you skip adding the statement, the test continues to run leading to a timeout.

Step 4 - Run the sample test code

After the test script is created, you can then run the file using the Run command in your IDE.

Step 5 - View the test results

After the test runs successfully, you can view the result on your command-line and the Automate dashboard. On the Automate dashboard, you can view the status of the test. You can also review the text logs, screenshots, and a video recording of your test execution.

BrowserStack Automate Test Results

Note: To learn about logs available in BrowserStack, check out Debugging Options.

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback

Is this page helping you?

Yes
No

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback!

Talk to an Expert
Talk to an Expert