How to run Selenium 3 on Docker

HOME

What is Docker and Container?

Docker is an open platform for developing, shipping, and running applications.
Docker provides the ability to package and run an application in a loosely isolated environment called a container. A container is a runnable instance of an image. You can create, start, stop, move, or delete a container using the Docker API or CLI. You can connect a container to one or more networks, attach storage to it, or even create a new image based on its current state.

By default, a container is relatively well isolated from other containers and its host machine
It contains multiple components such as Docker Daemon, Docker Clients, Docker Registry, and Docker Compose. It works on a client-server architecture. The Docker client communicates with the Docker Daemon handles the complex part of building, running, and distributing the Docker containers.

Docker Desktop is an easy-to-install application for your Mac or Windows environment that enables you to build and share containerized applications and microservices. Docker Desktop includes the Docker daemon (dockerd), the Docker client (docker), Docker Compose, Docker Content Trust, Kubernetes, and Credential Helper.

Why use Selenium with Docker for web application testing

When Selenium is used with Docker, there is no need to install the necessary browsers and browser drivers on the host machine. Overall, it is significantly quicker to get started with Selenium web automation testing using pre-made Docker containers. A range of Docker images (with Selenium) on the Docker Hub can be used by running a few commands on the terminal. Some of these images on the Docker Hub were developed and maintained by Selenium HQ.

One of the most common uses of Docker containers in selenium testing is cross-browser testing. Setting up test setups with all of the Browser-OS combinations gets difficult. These can be set up on the go and taken down once the tests are completed using Docker containers.

Another use of Docker containers in Selenium testing is parallel testing. Because there are so many sorts of tests to conduct, doing them sequentially takes a long time. As a result, parallelizing the testing saves time and provides faster feedback. Parallel testing, on the other hand, necessitates a significant amount of infrastructure setup. This would have a direct bearing on the price. Multiple containers can be launched on a single server using docker containers, making the most of the underlying hardware while also allowing for concurrent testing

Let’s discuss how to set up docker and run selenium tests on it.

Setting up Window Docker

Step 1 – Download the Docker Installer

Docker provides an installer for Windows which can be downloaded from the official docker website.

Step 2 – Install Docker

Launch the installer by double-clicking on it. Select the Enable Hyper-V Windows Features option on the configuration page.

If the user account and admin accounts are different, the user account must be added to the docker-users group as shown below:

To do that, you will need to run Computer Management as an administrator and navigate to Local Users and Groups > Groups > docker-users. Then right-click to add the user to the group. You will need to log and log back in for the changes to take effect.

Step 3 – Start Docker Desktop

After the installation process is complete, the tool does not start automatically. To start the Docker tool, search for the tool, and select Docker Desktop in your desktop search results or Docker desktop can be started from the start menu.

Docker is free for small businesses, personal usage, education and non-commercial purposes.

Step 4 – Verify the installation of Desktop Docker

To see if Docker is correctly configured, run the following line in Command Prompt. The version of Docker installed on the system is provided.

docker --version

Running Selenium Tests in Docker

The Docker Desktop can execute a few docker images after it is installed. You can either build a Docker image from the scratch, or start with a pre-configured base image from the Docker hub and add to it.

The selenium/standalone-firefox image hosted by selenium on DockerHub is used in this tutorial.

Step 1 – Pull the docker image

Run the following command to download a copy of the image onto the system.

docker pull selenium/standalone-firefox

Step 2 – Running the Selenium Webdriver Docker container

Upon pulling the selenium/standalone-firefox image onto the system, start the container by running the following command:

docker run -d -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-firefox

The above command starts a container from the image specified in detached mode (background mode). It also maps Port 4444 on the container to Port 4444 on your local browser.

Open the browser and navigate to http://localhost:4444/. It reflects Selenium Grid UI, as shown below.

Step 3 – Add the dependencies to the POM.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>SeleniumDockerDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <name>SeleniumDockerDemo</name>
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

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

  <dependency>
     <groupId>io.github.bonigarcia</groupId>
     <artifactId>webdrivermanager</artifactId>
     <version>5.1.0</version>
   </dependency>
  
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>
   
</dependencies>

Step 4 – Create a sample test

I have created a base class where the WebDriver is initialized and at the end is closed.

import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.MalformedURLException;
import java.net.URL;

public class BaseTest {
    protected static ThreadLocal<RemoteWebDriver> driver = new ThreadLocal<>();
    public static String remote_url_firefox = "http://localhost:4444/wd/hub";


    @Before
    public void setDriver() throws MalformedURLException {

        WebDriverManager.firefoxdriver().setup();
        FirefoxOptions options = new FirefoxOptions();
        options.addArguments("window-size=1920,1200");
        driver.set(new RemoteWebDriver(new URL(remote_url_firefox), options));
        driver.get().get("https://opensource-demo.orangehrmlive.com/");

    }

    public WebDriver getDriver() {
        return driver.get();
    }

    @After
    public  void closeBrowser() {
        driver.get().quit();
        driver.remove();
    }
}

The below class contains the various tests. The tests are related to verifying the login to the application, verifying the title of current page, verifying the error message generated on providing the invalid credentials, verifying the linkedIn link, verifying the heading of forgot password page.

import org.junit.Test;
import org.openqa.selenium.By;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class LoginPageTest extends BaseTest{

    @Test
    public void validCredentials() {

        getDriver().findElement(By.name("txtUsername")).sendKeys("Admin");
        getDriver().findElement(By.name("txtPassword")).sendKeys("admin123");
        getDriver().findElement(By.id("btnLogin")).click();
        String newPageText = getDriver().findElement(By.xpath("//*[@id='content']/div/div[1]/h1")).getText();
        System.out.println("newPageText :" + newPageText);
        assertEquals(newPageText,"Dashboard");

    }

    @Test
    public void invalidCredentials() {

        getDriver().findElement(By.name("txtUsername")).sendKeys("1234");
        getDriver().findElement(By.name("txtPassword")).sendKeys("12342");
        getDriver().findElement(By.id("btnLogin")).click();
        String actualErrorMessage = getDriver().findElement(By.id("spanMessage")).getText();
        System.out.println("Actual ErrorMessage :" + actualErrorMessage);
        assertEquals(actualErrorMessage,"Invalid credentials");

    }

    @Test
    public void loginPageHeading() {

        String loginText = getDriver().findElement(By.id("logInPanelHeading")).getText();
        System.out.println("Actual loginText :" + loginText);
        assertEquals(loginText,"LOGIN Panel");

    }

    @Test
    public void forgotPasswordPageHeading() {

        getDriver().findElement(By.xpath("//*[@id='forgotPasswordLink']/a")).click();
        String forgetPasswordTitle= getDriver().findElement(By.xpath(" //*[@id='content']/div[1]/div[2]/h1")).getText();
        System.out.println("Actual Page Title of Forgot Password Page :" + forgetPasswordTitle);
        assertEquals(forgetPasswordTitle,"Forgot Your Password?");
    }

    @Test
    public void verifyLinkedIn() {

        Boolean linkedInIcon = getDriver().findElement(By.xpath("//*[@id='social-icons']/a[1]/img")).isEnabled();
        System.out.println("Actual linkedIn Text :" + linkedInIcon);
        assertTrue(linkedInIcon);

    }

}

Step 5 – Executing the test case

To run it from the command prompt, open a command prompt and run the following command:

mvn clean test

Navigate to the sessions tab on the Selenium Grid UI upon running the command. It would reflect an active session.

The logs can be viewed in the command prompt as shown below:

The same test can be run using Chrome browser too. To the run the tests using chrome browser, we need to make 2 changes.

1 Firstly, download selenium/standalone-chrome image hosted by selenium on DockerHub.

Use the below command to pull the image in Docker

docker pull selenium/standalone-chrome

Start the container by running the following command:

docker run -d -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-chrome

2. Secondly make the changes in the test code.

WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();

Congratulations!!. The above steps allow running Selenium tests in Docker seamlessly. Happy Learning

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s