Integration of Cucumber with Selenium and JUnit

HOME

As we know Cucumber is a BDD Tool and Selenium Webdriver is use for the automation of web application. Imagine we need to build a test framework which can be used by business to understand the test scenarios and as well can test the web application. This can be achieved by integrating Cucumber with Selenium.

In this tutorial, I’ll create a BDD Framework for the testing of web applications using Selenium Webdriver . This framework consists of:-

  1. Cucumber
  2. Java 8 or above
  3. JUnit
  4. Maven
  5. Selenium

Steps to setup Cucumber Test Automation Framework with Selenium

  1. Download and Install Java on system
  2. Download and setup Eclipse IDE on system
  3. Setup Maven
  4. Create a new Maven Project
  5. Create source folder – src/test/resources to create test scenarios in Feature file
  6. Add Selenium and Cucumber dependencies to the project
  7. Add Maven Compiler Plugin
  8. Create a feature file under src/test/resources
  9. Create the Step Definition class or Glue Code
  10. Create a Cucumber Runner class
  11. Run the tests from JUnit
  12. Run the tests from Command Line
  13. Cucumber Report Generation

Step 1- Download and Install Java

Cucumber and Selenium needs Java to be installed on the system to run the tests. Click here to know How to install Java.

Step 2 – Download and setup Eclipse IDE on system

The Eclipse IDE (integrated development environment) provides strong support for Java developer. The Eclipse IDE for Java Developers distribution is designed to support standard Java development. It includes support for the Maven and Gradle build system and support for the Git version control system. Click here to know How to install Eclipse.

Step 3 – Setup Maven

To build a test framework, we need to add a number of dependencies to the project. It is very tedious and cumbersome process to add each dependency manually. So, to overcome this problem, we use a build management tool. Maven is a build management tool which is used to define project structure, dependencies, build, and test management. Click here to know How to install Maven.

Step 4 – Create a new Maven Project

Click here to know How to create a Maven project

Below is the Maven project structure. Here,

Group Id – com.cucumber
Artifact Id – seleniumdemo
Version – 0.0.1-SNAPSHOT
Package – com.cucumber.seleniumdemo

Maven Dependency (pom.xml) looks like something shown below for a new Maven project.

Step 5 – Create source folder src/test/resources to create test scenarios in Feature file

When a new Maven Project is created, it has 2 folders – src/main/java and src/test/java. To create test scenarios, we need a new source folder called – src/test/resources. To create this folder, right click on your maven project ->select New ->Java and then Source Folder.

Mention the source folder name as src/test/resources and click Next button. This will create a source folder under your new Maven project as shown in the below image.

Step 6 – Add Selenium and Cucumber dependencies to the project

Add below mentioned Selenium and Cucumber dependencies to the project.

 <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>6.8.1</version>
    </dependency>

<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-junit</artifactId>
      <version>6.8.1</version>
      <scope>test</scope>
     </dependency>

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
    </dependency>

Step 7 – Add Maven Compiler Plugin

The compiler plugin is used to compile the source code of a Maven project. This plugin has two goals, which are already bound to specific phases of the default lifecycle:

  • compile – compile main source files
  • testCompile – compile test source files
<build>
     <plugins>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>3.7.0</version>
         <configuration>
           <source>1.8</source>
           <target>1.8</target>
            <encoding>UTF-8</encoding>          
         </configuration>
       </plugin>                
       </plugins>
   </build>

The complete pom.xml will look like below image

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.cucumber</groupId>
  <artifactId>seleniumdemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>seleniumdemo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>6.8.1</version>
    </dependency>

<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-junit</artifactId>
      <version>6.8.1</version>
      <scope>test</scope>
     </dependency>

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
    </dependency>
    
    
  </dependencies>
  
   <build>
     <plugins>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>3.7.0</version>
         <configuration>
           <source>1.8</source>
           <target>1.8</target>
            <encoding>UTF-8</encoding>          
         </configuration>
       </plugin>                
       </plugins>
   </build>
</project>

Step 8 – Create a feature file (LoginPage.feature) containing all the test scenerios under src/test/resources/features

Feature file should be saved as an extension of .feature. Add the test scenarios in this feature file. I have added sample test scenarios. In this feature file, I have created a scenario for successful login and another one for failed login. The test scnerios are written in Gherkins language

Feature: Login to HRM Application 

   @ValidCredentials
   Scenario: Login with valid credentials
    
    Given User is on Home page
    When User enters username as "Admin"
    And User enters password as "admin123"
    Then User should be able to login sucessfully
    
   @InValidCredentials
   Scenario: Login with invalid credentials
    
    Given User is on Home page
    When User enters username as "username"
    And User enters password as "password"
    Then Login will be unsuccessfull with error message "Invalid credentials"

Step 9 – Create the stepdefinition class corresponding to the feature file to test the scenarios

public class LoginPagedefinition {

	WebDriver driver;

	@Given("User is on Home page")
	public void userOnHomePage() {
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\Vibha\\Desktop\\SeleniumKT\\chromedriver_win32\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		driver.get("https://opensource-demo.orangehrmlive.com/");
	}

	@When("User enters username as {string}")
	public void entersUsername(String userName) throws InterruptedException {

		System.out.println("Username Entered");
		driver.findElement(By.name("txtUsername")).sendKeys(userName);

	}

	@When("User enters password as {string}")
	public void entersPassword(String passWord) throws InterruptedException {

		System.out.println("Password Entered");
		driver.findElement(By.name("txtPassword")).sendKeys(passWord);

		driver.findElement(By.id("btnLogin")).submit();
	}

	@Then("User should be able to login sucessfully")
	public void sucessfullLogin() throws InterruptedException {

		String newPageText = driver.findElement(By.id("welcome")).getText();
		System.out.println("newPageText :" + newPageText);
		assertThat(newPageText, containsString("Welcome"));

	}

	@Then("Login will be unsuccessfull with error message {string}")
	public void unsucessfullLogin(String errorMessage) throws InterruptedException {

		String actualErrorMessage = driver.findElement(By.id("spanMessage")).getText();
		System.out.println("Actual Error Message :" + actualErrorMessage);

		assertTrue(actualErrorMessage.equalsIgnoreCase(errorMessage));

	}
}

Step 10 – Create a Cucumber Runner class to execute the test scenarios

We need to create a class called Runner class to run the tests. This class will use the JUnit annotation @RunWith(), which tells JUnit what is the test runner class.

package com.cucumber.seleniumdemo.runner;

import org.junit.runner.RunWith;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)
@CucumberOptions(features = {
		"src/test/resources/features/LoginPage.feature" }, glue = "com.cucumber.seleniumdemo.definition")

public class CucumberRunnerTest {

}

Step 11 – Test Execution through JUnit

Go to Runner class and right click Run As Junit. The tests will run as JUnit tests.

Step 12 – Run the tests from Command Line

Run the below command in command prompt to run t he tests and to get the test execution report.

mvn test

The execution screen looks like something as shown below

Step 13 – Cucumber Report Generation

To get Cucumber Test Reports, add cucumber.properties under src/test/resources and add the below instruction in the file

cucumber.publish.enabled=true

Below is the image of the Cucumber Report generated using Cucumber Service

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

One thought on “Integration of Cucumber with Selenium and JUnit

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 )

Google photo

You are commenting using your Google 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