Blog Automation Testing

Selenium WebDriver Tutorial: How to Start Automation Testing using Selenium and Cucumber Framework

August 29, 2023
Selenium WebDriver Tutorial

In the world of software testing, Selenium WebDriver has emerged as the most used tool for automating web applications. Along with the Cucumber framework, it provides a seamless environment for Behavior-Driven Development (BDD) testing. 

In this post, we will guide you through the process of setting up your automation testing using Selenium WebDriver and Cucumber, while also delving into key aspects like cross-browser testing, parallel testing, Jenkins integration, test suite management, and test data management.

Getting Started with Selenium WebDriver and Cucumber

Before starting the setup process let’s understand basics about Selenium & Cucumber.:

1. Selenium WebDriver: 

Selenium is an open-source testing framework that allows you to automate actions performed by users on a web application. WebDriver, a part of Selenium, provides a browser-specific driver to interact with web elements. The official website for Selenium is: https://www.selenium.dev/

2. Cucumber Framework: 

Cucumber is a BDD tool that enables collaboration between developers and non-developers (testers, business analysts, etc.) in the testing process. It uses a simple syntax to write human-readable test scenarios.The official website for Cucumber is: https://cucumber.io/

To demonstrate these concepts, we will use a demo script available at https://qa-practice.netlify.app/bugs-form . Let’s go through the steps of writing and executing a test scenario.

Writing and Executing a Test Scenario

Let’s try to understand a scenario where we need to test the functionality of a registration form on a web page. Let’s walk through the different steps on setting up the project and executing demo scripts.

Set Up Your Project

Start by creating a Maven or Gradle project and add the necessary dependencies:

  • Selenium WebDriver
  • Cucumber
  • Cucumber JVM
  • JUnit (for running tests)

Feature File

Create a feature file (e.g., registration.feature) with the test scenario in Gherkin syntax:


Feature: User Registration
  Scenario: Successful user registration
    Given I am on the registration page
    When I fill in the registration form
    And I click the Register button
    Then I should see a successful registration message
  1. Feature:
    This keyword is used to define the high-level description of the feature you’re testing. It’s followed by a colon and the name of the feature. In this case, the feature is “User Registration.”

  2. Scenario:
    This keyword is used to define individual test scenarios within a feature. It’s followed by a colon and the name of the scenario. In this case, the scenario is “Successful user registration.”

  3. Given:
    This is a step definition in the Gherkin language that represents the initial context or setup of the test. It’s used to describe the starting point of the scenario. In this case, “I am on the registration page” is the Given step. It usually involves setting up the initial conditions or state of the system.

  4. When:
    This is a step definition that represents an action taken by the user or the system. It describes an event that occurs as part of the test scenario. In this case, “I fill in the registration form” is the When step. It typically involves interacting with the system or performing an action.

  5. And:
    In Gherkin, the And keyword is used to continue a step definition without specifying a new keyword like Given, When, or Then. It’s used to add more steps to a Given, When, or Then section. In this case, “I click the Register button” is an And step, and it’s an extension of the When step.

  6. Then:
    This step definition represents an expected outcome or result of the test scenario. It’s used to define the verification step to confirm that the system behaves as expected. In this case, “I should see a successful registration message” is the Then step. It usually involves assertions or verifications.

These annotations are part of the Gherkin language, which is a human-readable domain-specific language used to define test scenarios in a structured and understandable format. Cucumber then maps these Gherkin statements to the actual step definitions in your code using regular expressions or other mechanisms. This way, the business stakeholders, developers, and testers can collaborate effectively using a common language to define and understand the behavior of the system.

Step Definitions

Create step-definition classes for your scenarios. For the example scenario above, you might have a class like RegistrationSteps.java:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.en.*;

public class RegistrationSteps {

    private WebDriver driver;

    @Given(“I am on the registration page”)
    public void iAmOnRegistrationPage() {
        System.setProperty(“webdriver.chrome.driver”, “path_to_chromedriver.exe”);
        driver = new ChromeDriver();
        driver.get(“https://qa-practice.netlify.app/bugs-form”);
    }

    @When(“I fill in the registration form”)
    public void iFillRegistrationForm() {
        WebElement firstNameField = driver.findElement(By.id(“firstName”));
        firstNameField.sendKeys(“John”);

        WebElement lastNameField = driver.findElement(By.id(“lastName”));
        lastNameField.sendKeys(“Doe”);

        WebElement emailField = driver.findElement(By.id(“email”));
        emailField.sendKeys(johndoe@example.com);

        WebElement phoneNumberField = driver.findElement(By.id(“phoneNumber”));

        phoneNumberField.sendKeys(“1234567890”);



        // Similarly, fill in other form fields
    }

    @And(“I click the Register button”)
    public void iClickRegisterButton() {
        WebElement registerButton = driver.findElement(By.id(“registerBtn”));
        registerButton.click();
    }

    @Then(“I should see a successful registration message”)
    public void iSeeSuccessfulRegistrationMessage() {
        WebElement successMessage = driver.findElement(By.id(“successMessage”));
        String actualMessage = successMessage.getText();

        assertTrue(actualMessage.contains(“Successfully registered the following information”));
        // You can add more assertions or verifications here
    }

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

Runner Class

Create a runner class to execute your Cucumber scenarios. For example, TestRunner.java:

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
    features = “src/test/resources”,
    glue = “path.to.step.definitions”,
    plugin = {“pretty”, “html:target/cucumber”}
)
public class TestRunner {
}

Replace path.to.step.definitions with the actual package where your step definitions are located.

Run the Tests:

Run your tests using JUnit by executing the TestRunner class. This will execute the Cucumber scenarios you defined in the feature files. You can also execute using Java commands as below:

  • Open a terminal/command prompt.
  • Navigate to the directory where your RunnerTest class is located.
  • Use the following command to execute the runner class:
java -cp “path_to_classpath” cucumber.api.cli.Main –glue “package_with_step_definitions” “path_to_feature_files”

      Here,

  1. path_to_classpath should include the classpath to your compiled classes and necessary libraries.
  2. package_with_step_definitions is the package where your step definitions are located.
  3. path_to_feature_files is the path to the directory containing your feature files.

If you are using maven then simply use “mvn test”

Enhancing Software Testing Efficiency and Quality

To enhance the effectiveness of the Selenium framework, we need to ensure that it has support for cross-browser compatibility, parallel execution, efficient test data management, and Jenkins integration. Let’s briefly discuss each item.

Cross-Browser Compatibility: 

In today’s world, we are required to provide support for the web application across various browsers. However, each browser might interpret and display a website differently. Cross-browser compatibility testing is about ensuring that your application works smoothly across a range of browsers like Chrome, Firefox, Safari, and others. This is crucial to provide a consistent user experience for everyone, regardless of their browser choice. Using tools like Selenium WebDriver, you can automate these tests efficiently and catch compatibility issues early in the development cycle. The best combination is to do Selenium Grid with Docker setup for cross-browser testing.

Parallel Execution: 

As your test suite grows, the time needed to execute all tests can increase significantly. Parallel testing comes to the rescue by allowing multiple tests to run simultaneously. This reduces the overall execution time and provides faster feedback. It’s like having multiple workers complete tasks together, rather than one after the other. This approach not only saves time but also improves efficiency and helps you deliver your software faster.

Jenkins Integration: 

Jenkins is a popular automation server that can be incredibly valuable for software testing. It can automatically trigger test executions whenever new code is added or modified, ensuring that changes don’t break existing functionality. This integration is a core part of continuous testing in the CI/CD (Continuous Integration/Continuous Deployment) pipeline. By catching issues early and often, you can maintain a high level of code quality and deliver updates with confidence.

Efficient Test Management: 

Managing tests can become challenging as the number of tests increases. A well-organized test suite groups related tests together logically, making it easier to run specific tests or test suites. Additionally, efficient test data management is vital. Tests often require specific data to run, and managing this data separately from the tests themselves helps ensure consistency and reliability. By having a solid test management strategy, you can streamline testing processes and ensure comprehensive test coverage.

Conclusion

In this tutorial, we’ve explored the basics of setting up automation testing using Selenium WebDriver and Cucumber. We’ve walked through writing a test scenario, understanding step definitions, and the importance of cross-browser testing, parallel testing, Jenkins integration, test suite management, and test data management. This foundation will empower you to build robust automation frameworks that contribute to the quality and reliability of your software applications. Start your journey into automation testing and unlock new possibilities for efficient and effective software delivery.

Leave a Reply