Dockerize Your Selenium Grid Setup
If your tests pass locally and fail in higher environments, then the best way to ensure consistent behaviour for your tests with greater efficiency is to dockerize them.
In this article, we will first set up a Selenium Grid and then dockerize it.
Below is a quick intro to Docker containers.
Docker Desktop client
UI Test Project
Let's assume your Test Project uses TestNG to run its selenium scripts.
Step 1: Modify your BaseTest or Test starter class to initialize RemoteWebDriver.
Replace or add the below code to your BaseTest or wherever your Browser Driver initialization happens.
Step 2: Add Maven Plugins to your pom.xml to create executable jars.
We will need to add the below plugins in order to generate an executable jar for our Test Project.
However, by default maven packages only the source code under the main folder, and in case your Test Project has testing-related code under the main and test folders then we need to explicitly mention this in the pom.xml file.
[Your Test Project may follow the Page Object Model design pattern where your Page classes may reside in the main and Test classes under test folder.]
Refer to the execution goal at line 51 in the below image.
Step 3: Add a healthcheck.sh script
The healthcheck script is needed to check the Grid availability to receive test requests before running our tests.
Step 4: Add a run.sh script
This script will execute the jar files containing tests.
Step 5: Create a docker-compose.yml file
The below docker-compose file will let you run Selenium Grid with all its components.
Step 6: Create a Dockerfile to instruct the creation of your Docker Image
We will use multiple base images in multi-stage builds to create the final image. The first stage (named package) will generate the executable jars and the second stage (named testrun) will run these executable jars.
Do note the different base images being used in each stage as required.
Note: The above Dockerfile contains many RUN and shell commands listed separately for ease of understanding; however, we can combine them or run them together.
A smarter approach would be to use a Dockerfile Linter to ensure that the Dockerfile is written with the best practices. e.g. Hadolint
Step 7: Finally, run your docker-compose
Open Powershell in your project root folder and run the below command.
docker-compose up --build
Bonus: One can also dockerize their whole Automation Framework which may include API tests too. Just modify the testng.xml accordingly to include the required tests.
Link to my GitLab project used in this example:
The project contains a lightweight framework capable of running both UI and API tests.