Selenium and Java

Applies to CrossBrowserTesting SaaS, last modified on January 10, 2023

Getting started with Selenium and Java

Selenium is a great tool to automate our functional tests on websites and web applications in our favorite language. With CrossBrowserTesting, you can use Selenium and Java to run automated browser tests on thousands of real mobile and desktop browsers in the cloud. To learn more about the Selenium API, we recommend you read Selenium documentation.

Note: You will need a Username and Authkey to run your tests on CrossBrowserTesting To get yours, sign up for a free trial or purchase a plan.

Install Selenium

To get started, make sure you have Selenium's language bindings for Java installed and ready. You can find the official resource for this here:

http://www.seleniumhq.org/download/

Or, for easier setup you can import the following dependency to Maven:

org.seleniumhq.selenium
selenium-java
3.141.59

To learn more about the Selenium API, we recommend which Selenium's documentation which can be found here:

Getting started: http://docs.seleniumhq.org/docs/03_webdriver.jsp

Run our first test

Once you have everything ready, let us try running our first automated test with CrossBrowserTesting! Copy and paste the following code into your text-editor/compiler of choice, and try running your test:

package com.mycompany.app;

import java.net.URL;

import org.junit.Before;
import org.junit.Test;
import org.junit.After;
import org.junit.Assert;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.util.HashMap;

public class CBTTest {
    private RemoteWebDriver driver;
    private CBTAPI api;
    private String score;

    @Before
    public void setUp() throws Exception {
        String username = System.getenv("CBTUSRNAME").replaceAll("@", "%40");
        String authkey = System.getenv("CBTAUTH");
        System.out.println(username);

        DesiredCapabilities caps = new DesiredCapabilities();
        HashMap<String, String> cbtoptions = new HashMap<String, String>();

        cbtoptions.put("record_video", "true");
        cbtoptions.put("screenResolution", "1366x768");
        caps.setCapability("name", "CBT Java");
        caps.setCapability("browserName", "Chrome");
        caps.setCapability("browserVersion", "84");
        caps.setCapability("platformName", "Windows 10");
        caps.setCapability("cbt:options", cbtoptions);


        api = new CBTAPI(username, authkey);

        String hubAddress = String.format("http://%s:%[email protected]:80/wd/hub", username, authkey);
        URL url = new URL(hubAddress);
        driver = new RemoteWebDriver(url, caps);
        // record a video using the API instead of the capabilities above.
        api.record_video(driver.getSessionId().toString());
    }

    @Test
    public void testToDo() {
        // test 1: Get title.
        driver.get("https://www.whatsmybrowser.org");
        // test 2:check what title equals.
        Assert.assertEquals("What browser am I using?", driver.getTitle());
        System.out.println(driver.getTitle());
        score = "Pass";
    }

    @After
    public void tearDown() throws Exception {
        if (driver != null) {
            // Set the score depending on the tests.
            api.setScore(score, driver.getSessionId().toString());
            driver.quit();
            System.out.println(score);
        }
    }
}

API calls (from above code)

The API calls below (CBTAPI.java) should be in the same directory as the above file (CBTTest.java).

package com.mycompany.app;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class CBTAPI {
    private String username, authkey;

    public CBTAPI(String username, String authkey) {
        this.username = username; // Your username
        this.authkey = authkey; // Your authkey
    }

    public void setScore(String score, String seleniumSessionId) throws UnirestException {
        HttpResponse response = Unirest.put("http://crossbrowsertesting.com/api/v3/selenium/{seleniumSessionId}")
                            .basicAuth(username, authkey)
                            .routeParam("seleniumSessionId", seleniumSessionId)
                            .field("action","set_score")
                            .field("score", score)
                            .asJson();
    }

    public void record_video(String seleniumSessionId) throws UnirestException {
        HttpResponse response = Unirest.post("http://crossbrowsertesting.com/api/v3/selenium/{seleniumSessionId}/videos")
                            .basicAuth(username, authkey)
                            .routeParam("seleniumSessionId", seleniumSessionId)
                            .asJson();
    }
    
}

Test capabilities

CrossBrowserTesting allows you to add certain capabilities to your test, like video recordings, naming structure and more.

Name tests

Naming your tests can help organize your automated test cases for easier debugging. You can also mark Build number to denote releases.

caps.setCapability("name", "Selenium Test Example");
caps.setCapability("build", "1.0");

Choose browsers

To choose your environment, you can select from Browsers, Operating System, Resolutions, and Devices. You can use our easy Selenium Wizard to select your configuration or hit our browser list endpoint.

Record videos

For superior debugging capabilities, CrossBrowserTesting offers the ability to record a video of your Selenium test session. You can find a copy of your test results here.

caps.setCapability("record_video", "true");

Record network

To record the network packets during your test for performance debugging, set the following to "true".

caps.setCapability("record_network", "true");

Run a local test

With our Local Tunnel, you can run a test on a local URL or behind your company's firewall. There are two different ways to connect the CrossBrowserTesting local tunnel: our Node.js client and our Chrome Extension.

To learm more about setting up, starting, and using your tunnel connection, see About Local Testing.

When a tunnel is open, any automated test can access websites locally, behind a firewall, or across a proxy. There is no need to set a capability during your test.

Troubleshooting

Waits

One of the most common errors in Selenium is caused by a page not being fully loaded before making assertions crucial to the passing or failing score of your test. Selenium provides two basic ways of performing waits that force your test to pause before continuing the next in a sequence of steps. This will help prevent that pesky ElementNotVisibleException that causes so many false negatives.

Selenium’s Java Bindings divides waits into implicit and explicit categories. An implicit wait pauses the test for a set amount of time until it is expected that a given condition will already true. The following code snippet makes use of the implicit wait method of WebDriver before making an assertion in regard to the title of the web page:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;




RemoteWebDriver driver = new RemoteWebDriver(new URL("http://" + username + ":" + authkey +"@hub.crossbrowsertesting.com:80/wd/hub"), capabilities[i]);

driver.get(“http://www.crossbrowsertesting.com”)
driver.manage().timeouts.implicitlyWait(10, TimeUnit.SECONDS);

assertEquals(driver.getTitle(), “CrossBrowser Testing App”);

Explicit waits pause test execution until a certain condition has been met. In order to successfully perform an explicit wait with Java’s Selenium bindings, we need to instantiate a wait object and make use of its “until” method as shown below:

import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.By;

driver.get(“www.crossbrowsertesting.com”);
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement elem = wait.until(ExpectedConditions.elementToBeClickable(By.class(“mkt-btn center btn-orange”)));

CBTHelper Java

Getting started with CrossBrowserTesting and Selenium using the Java language can be easily done with the help of CBTHelper java. CBTHelper Java is a Maven dependency that aims to make the use of the CrossBrowserTesting API user-friendly.

To get started you will need to include this dependency in you pom.xml:

<dependency>
<groupId>com.crossbrowsertesting</groupId>
<artifactId>CBT_Helper</artifactId>
<version>1.0.0</version>
</dependency>

Useful functions

Easily take a snapshot:

takeSnapshot()

Set the description of a video or snapshot:

setDescription(String description)

Generate the desired selenium capabilities:

CapsBuilder(String username, String authkey)

To save the current snapshot or video on your machine:

saveLocally(String location)

Set the score for the test:

setScore(String score)

Full segment

In order to get started, simply copy the following script into a text editor of your choice and add your CrossBrowserTesting username and authkey. Make sure to use "%40" in place of "@" since the username is not automatically encoded.

package com.mycompany.app;

import com.mashape.unirest.http.exceptions.UnirestException;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
import com.crossbrowsertesting.CapsBuilder;
import com.crossbrowsertesting.AutomatedTest;
import com.crossbrowsertesting.Video;
import com.crossbrowsertesting.Snapshot;
import com.crossbrowsertesting.Builders;

/**
 *
 * @author CBT
 */

public class App {
    public static void main(String[] args) throws Exception{


      Builders builder = new Builders();
      //be sure to use %40 not @ here
      builder.login("your-email%40company.com", "your-password");

      //Build the caps for our driver
      CapsBuilder capsBuilder = new CapsBuilder(builder.username, builder.authkey);
      capsBuilder.withPlatform("Mac OSX 10.14").withBuild("1.0").withBrowser("Safari12").build();

      RemoteWebDriver driver = new RemoteWebDriver(new URL("http://" + builder.username + ":" + builder.authkey + "@hub.crossbrowsertesting.com:80/wd/hub"),capsBuilder.caps);
      
      //initialize an AutomatedTest object with our selenium session id
      AutomatedTest myTest = new AutomatedTest(driver.getSessionId().toString());

      //start up a video
      Video video = myTest.startRecordingVideo();


      driver.get("http://google.com");

      //take a snapshot of where we currently are
      Snapshot googleSnap = myTest.takeSnapshot();
      googleSnap.setDescription("google.com");
      googleSnap.saveLocally("test/google.png");

      driver.get("http://crossbrowsertesting.com");

      //take a snapshot and set description all at once
      myTest.takeSnapshot("cbt.com");

      //stop our video and set a description
      video.setDescription("google and cbt video");
      video.stopRecording();

      //set a score for our test and end it
      myTest.setScore("pass");
      myTest.stop();

      //save our video
      video.saveLocally("test/myvideo.mp4");

    }
}

See Also

Selenium and C#
Selenium and Python

Highlight search results