Skip to main content

Selenium with JUnit

Your guide to run Selenium Webdriver tests with JUnit on BrowserStack.

Important: Sample test scripts are available in the junit-browserstack repository.

The sample test script in this section is compatible with JSON wire protocol-based client bindings. Check out our W3C-based scripts in the selenium-4 branch of the repository.

Introduction

BrowserStack gives you instant access to our Selenium Grid of 3000+ real devices and desktop browsers. Running your Selenium tests with JUnit on BrowserStack is simple. This guide will help you:

  1. Run your first test
  2. Understand your tests with BrowserStack
  3. Integrate your tests with BrowserStack
  4. Mark tests as passed or failed
  5. Debug your app

Prerequisites

  • You need to have BrowserStack Username and Access key, which you can find in your account settings. If you have not created an account yet, you can sign up for a Free Trial or purchase a plan.
  • Maven is installed on your machine, Maven environment variables are set, and Maven bin is added to the system path $PATH. Check out the official website to download the latest version of Maven.
  • Git is installed on your machine.

Run your first test

To run Selenium tests with JUnit on BrowserSatck Automate, follow the below steps:

  1. Clone the junit-browserstack repository using the following command:

     git clone https://github.com/browserstack/junit-browserstack.git
    
  2. Run the following command to install the dependencies::

     cd junit-browserstack/junit-4
     mvn install
    
  3. Set your BrowserStack Username and Access Key in the parallel.conf.json file, located inside the junit-4/src/test/resources/conf/ directory, as follows:

    This file also contains the capabilities that define the browsers and devices to run the test.

     {
       "server": "hub.browserstack.com",
       "user": "YOUR_USERNAME",
       "key": "YOUR_ACCESS_KEY",
       "capabilities": {
         "build": "junit-browserstack",
         "name": "parallel_test",
         "browserstack.debug": true
       },
       "environments": [
         {
           "browser": "chrome"
         },
         {
           "browser": "firefox"
         },
         {
           "browser": "safari",
           "os": "OS X"
         },
         {
           "browser": "Internet Explorer"
         },
         {
           "device": "Samsung Galaxy S21"
         },
         {
           "device": "iPhone 12"
         }
       ]
     }
    
  4. Run your first test on BrowserStack using the following command:

     mvn test -P parallel
    
  5. Navigate to your Automate Dashboard and view the tests running in parallel on multiple browsers.

Understand details of your first test

When you run the mvn test -P parallel command, the SingleTest.java file within the junit-browserstack/junit-4/src/test/java/com/browserstack/ directory is executed on several browsers, namely Chrome, Firefox, Safari, and Internet Explorer.

When the test is triggered, it:

  • Opens the bstackdemo.com website.
  • Adds a product to the cart.
  • Verifies whether the product is added to the cart.
  • Marks the test as passed or failed based on whether the product is available in the cart.
junit-browserstack/junit-4/src/test/java/com/browserstack/SingleTest.java
public class SingleTest extends BrowserStackJUnitTest {

  @Test
  public void test() throws Exception {
    SessionId sessionId = ((RemoteWebDriver) driver).getSessionId();

    try {
      driver.get("https://bstackdemo.com/");
      final WebDriverWait wait = new WebDriverWait(driver, 10);
      wait.until(ExpectedConditions.titleIs("StackDemo"));
      String product_name = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='1']/p"))).getText();
      WebElement cart_btn = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='1']/div[4]")));
      cart_btn.click();
      wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("float-cart__content")));
      final String product_in_cart = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='__next']/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]"))).getText();
      assertTrue(product_name.matches(product_in_cart));
      mark(sessionId, "passed", "Product has been successfully added to the cart!");

    } catch (Throwable t) {
      mark(sessionId, "failed", "There was some issue!");
      System.out.println("Exception: " + t);
    }
  }
}

The Parallelized.java file inside the junit-browserstack/junit-4/src/test/java/com/browserstack directory is used to run tests in parallel.

junit-browserstack/junit-4/src/test/java/com/browserstack/Parallelized.java
package com.browserstack;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;

public class Parallelized extends Parameterized {

  private static class ThreadPoolScheduler implements RunnerScheduler {
    private ExecutorService executor;

    public ThreadPoolScheduler() {
      String threads = System.getProperty("junit.parallel.threads", "16");
      int numThreads = Integer.parseInt(threads);
      executor = Executors.newFixedThreadPool(numThreads);
    }

    @Override
    public void finished() {
      executor.shutdown();
      try {
        executor.awaitTermination(10, TimeUnit.MINUTES);
      } catch (InterruptedException exc) {
        throw new RuntimeException(exc);
      }
    }

    @Override
    public void schedule(Runnable childStatement) {
      executor.submit(childStatement);
    }
  }

  public Parallelized(Class klass) throws Throwable {
    super(klass);
    setScheduler(new ThreadPoolScheduler());
  }
}

Integrate your tests with BrowserStack

The BrowserStackJUnitTest.java file defines methods used to configure and create a connection with BrowserStack for integrating your existing test suites as follows:

junit-browserstack/junit-4/src/test/java/com/browserstack/BrowserStackJUnitTest.java
@RunWith(Parallelized.class)
public class BrowserStackJUnitTest {
    public static String username, accessKey;
    private static JSONObject config;
    public WebDriver driver;
    @Parameter(value = 0)
    public int taskID;
    private Local l;

    @Parameters
    public static Iterable<? extends Object> data() throws Exception {
      List<Integer> taskIDs = new ArrayList<Integer>();

      if (System.getProperty("config") != null) {
        JSONParser parser = new JSONParser();
        config = (JSONObject) parser.parse(new FileReader("src/test/resources/conf/" + System.getProperty("config")));
        int envs = ((JSONArray) config.get("environments")).size();

        for (int i = 0; i < envs; i++) {
          taskIDs.add(i);
        }
      }

      return taskIDs;
    }

    public static void mark(SessionId sessionID, String status, String reason) throws URISyntaxException, IOException {
      URI uri = new URI("https://" + username + ":" + accessKey + "@api.browserstack.com/automate/sessions/" + sessionID + ".json");
      HttpPut putRequest = new HttpPut(uri);

      ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      nameValuePairs.add((new BasicNameValuePair("status", status)));
      nameValuePairs.add((new BasicNameValuePair("reason", reason)));
      putRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      HttpClientBuilder.create().build().execute(putRequest);
    }

    @Before
    public void setUp() throws Exception {
      JSONArray envs = (JSONArray) config.get("environments");

      DesiredCapabilities capabilities = new DesiredCapabilities();

      Map<String, String> envCapabilities = (Map<String, String>) envs.get(taskID);
      Iterator it = envCapabilities.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        capabilities.setCapability(pair.getKey().toString(), pair.getValue().toString());
      }

      Map<String, String> commonCapabilities = (Map<String, String>) config.get("capabilities");
      it = commonCapabilities.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        if (capabilities.getCapability(pair.getKey().toString()) == null) {
          capabilities.setCapability(pair.getKey().toString(), pair.getValue().toString());
        }
      }

      username = System.getenv("BROWSERSTACK_USERNAME");
      if (username == null) {
        username = (String) config.get("user");
      }

      accessKey = System.getenv("BROWSERSTACK_ACCESS_KEY");
      if (accessKey == null) {
        accessKey = (String) config.get("key");
      }

      if (capabilities.getCapability("browserstack.local") != null && capabilities.getCapability("browserstack.local") == "true") {
        l = new Local();
        Map<String, String> options = new HashMap<String, String>();
        options.put("key", accessKey);
        l.start(options);
      }

      driver = new RemoteWebDriver(new URL("https://" + username + ":" + accessKey + "@" + config.get("server") + "/wd/hub"), capabilities);
    }

    @After
    public void tearDown() throws Exception {
      driver.quit();
      if (l != null) l.stop();
    }
}

Mark tests as passed or failed

BrowserStack provides a comprehensive REST API to access and update information about your tests. Shown below is a sample code snippet which allows you to mark your tests as pass or fail based on the assertions in your JUnit test cases.

public static void mark(SessionId sessionID, String status, String reason) throws URISyntaxException, IOException {
  URI uri = new URI("https://" + username + ":" + accessKey + "@api.browserstack.com/automate/sessions/" + sessionID + ".json");
  HttpPut putRequest = new HttpPut(uri);

  ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
  nameValuePairs.add((new BasicNameValuePair("status", status)));
  nameValuePairs.add((new BasicNameValuePair("reason", reason)));
  putRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

  HttpClientBuilder.create().build().execute(putRequest);
}

You can find the full reference to our REST API.

Debug your app

BrowserStack provides a range of debugging tools to help you quickly identify and fix bugs you discover through your automated tests.

Text logs

Text Logs are a comprehensive record of your test. They are used to identify all the steps executed in the test and troubleshoot errors for the failed step. Text Logs are accessible from the Automate dashboard or via our REST API.

Visual logs

Visual Logs automatically capture the screenshots generated at every Selenium command run through your JUnit tests. Visual Logs help with debugging the exact step and the page where failure occurred. They also help identify any layout or design related issues with your web pages on different browsers.

Visual Logs are disabled by default. In order to enable Visual Logs you will need to set browserstack.debug capability to true.

"capabilities": {
  "browserstack.debug": true
}

Sample Visual Logs from Automate Dashboard: BrowserStack Automate Visual Logs

Video recording

Every test run on the BrowserStack Selenium grid is recorded exactly as it is executed on our remote machine. This feature is particularly helpful whenever a browser test fails. You can access videos from Automate Dashboard for each session. You can also download the videos from the Dashboard or retrieve a link to download the video using our REST API.

Note: Video recording increases test execution time slightly. You can disable this feature by setting the browserstack.video capability to false.
"capabilities": {
  "browserstack.video": false
}

In addition to these logs BrowserStack also provides Raw Logs, Network Logs, Console Logs, Selenium Logs, Appium Logs and Interactive session. You can find the complete details to enable all the debugging options.

Next steps

Once you have successfully run your first test on BrowserStack, you might want to do one of the following:

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