NashTech Blog

Container Specflow with Docker Container

Table of Contents

I. Docker Introduction:

Docker is a containerization platform that packages an application and its dependencies into a standardized unit called a container. Containers are lightweight, portable, and isolated environments that include everything needed to run the application: code, runtime, system tools, libraries, and settings. This enables applications to run consistently across different environments, from development to testing to production.

II. The advantages of containerizing a Selenium test with Docker:

Containerizing a Selenium test with Docker offers several advantages, primarily revolving around consistency, scalability, isolation, and ease of deployment. Here are the key advantages:

  1. Consistency in Development and Testing Environments:
    • Docker containers encapsulate the entire runtime environment, including dependencies and configurations. This ensures that the Selenium tests run consistently across different development machines and testing environments, reducing the likelihood of “works on my machine” issues.
  2. Isolation and Dependency Management:
    • Each Docker container runs in isolation from other containers and the host system. This isolation prevents conflicts between different versions of dependencies or libraries that might be used in different projects or tests.
  3. Scalability and Resource Efficiency:
    • Docker containers are lightweight and use OS-level virtualization, allowing for efficient use of system resources. Multiple containers can be spun up concurrently to execute tests in parallel, improving test execution speed and scalability.
  4. Easy Deployment and Version Control:
    • Docker containers are portable and can be deployed consistently across different environments, including local development machines, CI/CD pipelines, and production servers. This simplifies the deployment process and ensures that the same containerized application runs everywhere.
  5. Simplified Dependency Installation and Setup:
    • With Docker, you can define the entire environment setup, including Selenium WebDriver and browser versions, in a Dockerfile. This eliminates the need for manual setup and configuration on each developer’s machine or testing environment.
  6. Reproducibility and Version Consistency:
    • Docker images are built from Dockerfiles, which specify the exact steps to create the environment. This ensures that the environment is reproducible across different stages of the software development lifecycle, maintaining version consistency.
  7. Enhanced Collaboration and Team Productivity:
    • Docker simplifies collaboration by providing a standardized environment that all team members can use. It reduces onboarding time for new team members and makes it easier to share and replicate testing environments.
  8. Security and Isolation Benefits:
    • Docker containers provide a level of isolation that enhances security by limiting the surface area of potential attacks. Each container operates independently, reducing the impact of security vulnerabilities.

III. Prepare Selenium test project:

Below, I’ll guide you through setting up a basic SpecFlow project using Visual Studio Code, C#, Selenium, and SpecFlow extensions

Initialize a New .NET Core Console Project:

Open your terminal (integrated terminal in VS Code or your system’s terminal) and follow these steps:


# Initialize a new .NET Core console project
dotnet new console -n SpecFlowSeleniumExample
cd SpecFlowSeleniumExample

Add Necessary Packages:

Open SpecFlowSeleniumExample.csproj file in VS Code and add the following package references:


<Project Sdk="Microsoft.NET.Sdk">

      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>

      <ItemGroup>
          <None Update="specflow.json">
            <CopyToOutputDirectory>Always</CopyToOutputDirectory>
          </None>
      </ItemGroup>

      <ItemGroup>
        <PackageReference Include="Allure.SpecFlow" Version="2.12.1" />
        <PackageReference Include="NUnit" Version="3.13.2" />
        <PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
        <PackageReference Include="Selenium.WebDriver" Version="4.21.0" />
        <PackageReference Include="SpecFlow" Version="3.9.8" />
        <PackageReference Include="SpecFlow.NUnit" Version="3.9.8" />
        <PackageReference Include="SpecFlow.Tools.MsBuild.Generation" Version="3.9.8" />
        <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
        <PackageReference Include="NUnit.Analyzers" Version="3.3.0" />
        <PackageReference Include="coverlet.collector" Version="3.1.2" />
      </ItemGroup>

</Project>

Create specflow.json file, add Allure.SpecFlowPlugin as a step assembly.


{
  "stepAssemblies": [{ "assembly": "Allure.SpecFlowPlugin" }]
}

Write a Feature File:

Create a feature file (GoogleSearch.feature) in a Features directory within your project:


Feature: Google Search
    As a user
    I want to search for a term on Google
    So that I can find relevant information

    Scenario: Searching on Google
        Given I am on the Google search page
        When I enter "SpecFlow" into the search box
        And I click the Google search button
        Then I should see search results

Implement Step Definitions:

Create a step definition file (LoginSteps.cs) in a Steps directory within your project:


using TechTalk.SpecFlow;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;

namespace SpecFlowAllureExample.Steps
{
    [Binding]
    public class GoogleSearchSteps
    {
        private IWebDriver driver;

        [BeforeScenario]
        public void BeforeScenario()
        {
            var chromeDriverPath = "/usr/local/bin/chromedriver";

            // Set ChromeDriver options
            var chromeOptions = new ChromeOptions();
            chromeOptions.AddArgument("--headless"); // Run Chrome in headless mode (no GUI)
            chromeOptions.AddArgument("--no-sandbox");
            chromeOptions.AddArgument("--disable-dev-shm-usage");

            // Initialize ChromeDriver with options
            driver = new ChromeDriver(chromeDriverPath, chromeOptions);
        }

        [AfterScenario]
        public void AfterScenario()
        {
            driver.Close();
            driver.Quit();
        }

        [Given(@"I am on the Google search page")]
        public void GivenIAmOnTheGoogleSearchPage()
        {
            driver.Navigate().GoToUrl("https://www.google.com");
        }

        [When(@"I enter ""(.*)"" into the search box")]
        public void WhenIEnterIntoTheSearchBox(string searchText)
        {
            IWebElement searchBox = driver.FindElement(By.Name("q"));
            searchBox.SendKeys(searchText);
        }

        [When(@"I click the Google search button")]
        public void WhenIClickTheGoogleSearchButton()
        {
            IWebElement searchButton = driver.FindElement(By.Name("q"));
            searchButton.Submit();
        }

        [Then(@"I should see search results")]
        public void ThenIShouldSeeSearchResults()
        {
            Assert.IsTrue(driver.Title.Contains("SpecFlow"));
        }
    }
}

Create a Docker file:

Create a Dockerfile in the root directory of your project (SpecFlowAllureExample). This file contains instructions for building your Docker image.


# Use the official .NET Core SDK image as a base image
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build-env
ARG CHROMEDRIVER_VERSION
RUN apt-get update && \
    apt-get install -y openjdk-11-jdk \
    zip \
    unzip
# Install Allure command-line tools
RUN wget https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/2.17.1/allure-commandline-2.17.1.zip && \
    unzip allure-commandline-2.17.1.zip -d /opt && \
    ln -s /opt/allure-2.17.1/bin/allure /usr/bin/allure && \
    allure --version
# Set up ChromeDriver (or GeckoDriver for Firefox)
RUN apt update && apt install -y  \
apt-transport-https \
ca-certificates \
curl \
gnupg \
hicolor-icon-theme \
libcanberra-gtk* \
libgl1-mesa-dri \
libgl1-mesa-glx \
libpango1.0-0 \
libpulse0 \
libv4l-0 \
fonts-symbola \
--no-install-recommends \
&& curl -sSL https://dl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& echo "deb [arch=amd64] https://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list
RUN apt-get update && apt-get install -y google-chrome-stable && \
wget -q -O /tmp/chromedriver.zip https://storage.googleapis.com/chrome-for-testing-public/126.0.6478.63/linux64/chromedriver-linux64.zip && \
unzip /tmp/chromedriver.zip -d /usr/local/bin/ && \
mv /usr/local/bin/chromedriver-linux64/chromedriver /usr/local/bin/ && rm -rf /usr/local/bin/chromedriver-linux64 && \
chmod +x /usr/local/bin/chromedriver && \
rm /tmp/chromedriver.zip

# Set the working directory inside the container
WORKDIR /app

# Copy the project file and restore dependencies
COPY *.csproj ./
RUN dotnet restore

# Copy the remaining source code
COPY . ./

RUN dotnet build -c Release -o out
RUN dotnet test

CMD ["allure", "generate", "/app/bin/Debug/net6.0/allure-results", "-o", "/app/allure-report", "--clean"]

Explanation of Docker file:
  1. Base Image and Build Environment (FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build-env):
    • This sets up the .NET Core SDK 6.0 as the base image (build-env) for building and testing your .NET Core application.
  2. Installation of Dependencies:
    • OpenJDK 11: Required for running Allure command-line tools.
    • zip and unzip: Necessary utilities for handling zip files.
    • Allure: Downloads and installs Allure command-line tools (allure-commandline-2.17.1.zip).
  3. Setup ChromeDriver and Google Chrome:
    • Installs Google Chrome Stable version and ChromeDriver based on the specified CHROMEDRIVER_VERSION. It downloads ChromeDriver from Google's storage based on the version provided.
  4. Working Directory and Project Setup:
    • Sets /app as the working directory inside the container.
    • Copies the .csproj file and restores NuGet packages (dotnet restore).
    • Copies the entire source code (COPY . ./).
  5. Build and Test:
    • Build: Executes dotnet build -c Release -o out to build the .NET Core application in Release mode, outputting to the out directory.
    • Test: Runs dotnet test to execute tests defined in the project.
  6. Allure Report Generation (CMD ["allure", "generate", ...]):
    • Defines the command (CMD) to generate an Allure report after running tests. It specifies the location of the test results (/app/bin/Debug/net6.0/allure-results) and where to output the generated report (/app/allure-report).

Build Docker Image

Use docker build --build-arg CHROMEDRIVER_VERSION=126.0.6478.63 -t your-image-name . to build the Docker image (your-image-name can be any name you choose).

Run Docker Container

Execute docker run --rm -v /path/on/your/host:/app/allure-report your-image-name to run the Docker container, which will build your .NET Core project, execute tests, and generate an Allure report. Replace /path/on/your/host with the path on your local machine where you want to store the Allure report.

This Dockerfile encapsulates your .NET Core project setup along with dependencies like Allure and ChromeDriver, providing a portable and consistent environment for development, testing, and reporting. Adjust the versions and configurations as per your project's requirements.

Picture of Hai Pham

Hai Pham

I am a highly skilled and dedicated Senior Automation Test Engineer at Nashtech Vietnam with a passion for ensuring software quality and improving efficiency through automated testing. With 5 years of experience in automation testing and an additional 2 years specializing in performance testing, I have developed a strong expertise in delivering reliable and scalable solutions. My proficiency lies in leveraging automation libraries like Selenium and performance testing tools like JMeter to design, develop, and execute comprehensive test suites. I possess a deep understanding of software development life cycle (SDLC) methodologies and possess the ability to integrate testing seamlessly into the development process.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top