BDD And Cucumber Tutorial With Examples

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated March 7, 2024

This In-Depth Cucumber Tutorial Discusses BDD And its Benefits, Cucumber Framework, Environmental Settings, Test Script Creation, Cucumber Features, Reports, etc.:

Cucumber has become very popular and now it is widely used in the Software Testing Industry.

Pre-requisites– Intended recipients should have knowledge of  Scrum, Maven, TestNG, etc.

BDD And Cucumber Tutorial

Background Of BDD

In the TDD Framework of Agile methodology, we normally write the test cases first and then execute them. This is good to attain Test Coverage and make sure the build is ready for production.

However, we can enhance the TDD framework by introducing Behaviors, Features, etc. to the test and then execute the same. This enhancement to TDD is termed as BDD (Behavior Driven Development).

Benefits Of Behavior Driven Development(BDD)

Some benefits of using BDD are:

#1) Bridges the gap between business stakeholders and the technical team through a common platform. Hence, communication among the team becomes more transparent.

#2) Scenarios can be written by anyone including people from a client-side, a member of the business team, management, etc. Hence, the requirements, scenarios are getting covered.

#3) Developers will write the code conforming to the scenarios written in the BDD framework instead of writing/developing the code as per their understanding.

#4) Testing becomes sharper, time spent in the creation and subsequent execution of a test is saved, critical defects especially those, which can impact the business can be found in the front end itself.

#5) Code, documentation relating to BDD are easily understandable and maintainable as no other effort is required to maintain the code as the documents and its corresponding code are already related. Hence what is mentioned in the documentation i.e. scenarios, will have its corresponding code.

#6) Since we have very easy understandable scenarios, we can easily break them into tasks, sub-tasks, etc in a logical manner.

#7) The team can be more dynamic, agile as there is an upfront clarity about the scenarios, acceptance criteria and almost accurate test estimation.

#8) Very good platform for a New Joined to groom with the existing team both in terms of documentation and the code because of its simplicity.

#9) Not only helps in validating the scenarios (mostly UI, behavior-related) but it also helps in unit-level test cases.

#10) Also, it is useful to track the team’s progress from day one because the requirements and scenarios are clearly defined [something which the developers usually struggle to collect in TDD].

Hence implementation of BDD removes the assumption that “end client does not think about the importance of testing”, “client does not want to involve themselves in the testing activities”, etc.

BDD Tools

There are several testing tools that enable us to implement the BDD approach.

Such as:

  • Cucumber
  • SpecFlow
  • Jbehave
  • Lettuce
  • Concordion
  • FitNesse
  • BeanSpec
  • Easy B
  • Jdave
  • Givwenzen-flex
  • GivWenZen
  • Instinct
  • Tumbler-glass
  • Gospecify
  • Spectacular
  • dSpec
  • Specs
  • Steak
  • JSSpec

Among the above tools, Jbehave works quite similar to Cucumber, however, these are slightly different in terms of their implementation.

JBEHAVECUCUMBER

Supports storiesSupports Features
Very good documentationNo standard documentation
Supports composite stepsDoes not support composite steps
Not so flexibleFlexible in passing parameters
Does not support backgroundSupports background
Not so extensive reportsBetter formatting flexibility, built-in reports
Supports external data sourcesIt does not support external data sources
Developed using JavaDeveloped using Ruby

Why Cucumber?

Cucumber is used for writing all kinds of test cases especially Acceptance level test cases (about which end users are more concerned) written in a Behavioral Driven Development style. It supports the usage of language parsers such as Gherkin.

Originally, Cucumber was written using Ruby programming language and was developed especially for Ruby testing. But now, it is being supported by other programming languages such as Java.

Gherkin is being used as the language in which the test cases are written in a simple format and can also be read and modified by a non-technical user.

Apart from English, Cucumber supports other languages as well.

How Does Cucumber Work?

Coming to its working mechanism, first, we let the users (technical/non-technical) write their desired test cases( as features) using Gherkin syntax, once it is done we need to make sure they are approved so that they can go to the next level.

After that, we need to implement i.e. write scripts for each line(using a stepdef file) as mentioned in the feature file. Once the codes are being implemented, the next thing would be to run the scripts (using a runner file).

Environmental Setup

The environmental setup for Cucumber is slightly complex compared to working with any other tool like Eclipse or any other IDE.

Challenges

We need to make sure that the versions of Cucumber jars match with the installed Java version as well as the IDE in which we are currently working.

Environmental Settings

#1) Eclipse Cucumber Plugin: It helps the Eclipse to understand the Gherkin syntax and highlights the syntax of the feature file instead of a plain text.

We need to go to Eclipse >> Help >> Install new software >> Click on Add button >> Specify the location as this. The name says “Cucumber” and then click on OK and follow the rest installation process.

At last restart your IDE i.e.  Eclipse.

#2) Use Maven to have all the jars i.e. dependencies, plugins, etc as mentioned below.

<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</groupId>
  <artifactId>cucumber.example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>cucumber.example</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
   <dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.6.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-chrome-driver -->
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-chrome-driver</artifactId>
    <version>3.6.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-core -->
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-core</artifactId>
    <version>1.2.5</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>1.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/gherkin -->
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>gherkin</artifactId>
    <version>2.12.2</version>
    <scope>provided</scope>
</dependency>
<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.9</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.11-beta3</version>
		</dependency>
		<dependency>
			<groupId>xml-apis</groupId>
			<artifactId>xml-apis</artifactId>
			<version>2.0.2</version>
		</dependency>
 
		<dependency>
			<groupId>xerces</groupId>
			<artifactId>xercesImpl</artifactId>
			<version>2.8.0</version>
		</dependency>	
		
		<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-jvm-deps -->
		<dependency>
    	<groupId>info.cukes</groupId>
    	<artifactId>cucumber-jvm-deps</artifactId>
    	<version>1.0.5</version>
    	<scope>provided</scope>
		</dependency>
	</dependencies>
 
	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-surefire-plugin</artifactId>
					<version>2.18</version>
					<dependencies>
						<dependency>
							<groupId>org.apache.maven.surefire</groupId>
							<artifactId>surefire-junit47</artifactId>
							<version>2.18</version>
						</dependency>
					</dependencies>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

#3) Make sure if we do either Ctrl+s or perform Maven install.

#4) After that make sure to perform Maven build to avoid any dependency related error so that we don’t have any dependency, plugin, version mismatch error later.

#5) Once the above steps are done our environment is ready.

Writing Test Cases Using Cucumber

Cucumber includes the following three files:

  1. Feature file: Here we write the Features to be tested in Gherkin format i.e. Given When Then. We can even run the feature file to execute the test scripts written in the Stepdef file.
  2. Stepdef file: Once the Feature file is ready, each sentence of the Feature file can be further implemented over the Stepdef file.
  3. Runner File: This is just to execute the actual test script written over the Stepdef file by referring to the feature file. Apart from that, it has many other options for customization, reporting, selective execution, etc.

Here is a simple example of a Runner File

package runner;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
features="Features",
glue="com.Multi",
plugin={"html:target/cucumber-html-report", "json:target/cucumber.json",

"pretty:target/cucumber-pretty.txt","usage:target/cucumber-usage.json", "junit:target/cucumber-
results.xml"},

dryRun = false,
monochrome = true,
tags={"@Smoke,@Regression"}
)

public class Runner {

}

Creating Files For Cucumber

  • Stepdef file– Src/test/java >> New >> Others >> Cucumber>>StepDef class.
  • Feature file– Project>>New>>File>> specify name for the file with extension as ‘.feature’.
  • Runner file– It is similar to any other Java class creation but we may require implementing some method here.

Cucumber Features

Here are some of the basic features of Cucumber which, we will be implementing in our Test Script.

#1) Cucumber Hooks

These are the blocks of the code that runs before or after each scenario. So that we can define these, anywhere in our project. For Example, Step Definition.

As per the definition, these are just two annotation @After and @Before. In the console, we can see the blocks getting executed and giving clear output. We can also execute the hooks for specific Tags.

#2) Cucumber Tags

These are normally used over the feature file to classify the scenarios over the feature files as per their given tag name. We can have multiple tags for a given scenario in the feature file.

Tags are user-defined and we can give any name to it such as @Smoke, @Regression, etc.

#3) Cucumber Annotations

These are inbuilt to Cucumber. Normally tags are @Given, @When, @Then.

However, later if we need we can create our own annotation and then use it in our program. During execution, the matching glue code i.e. functions are written in a Stepdef file having @Given, @When, @Then will get executed.

#4) Cucumber Background

These are steps or series of steps that are common to all the scenarios in the feature file.

It allows us to add some context to the scenarios for a feature where it is defined. It runs before every scenario for a feature in which it is defined.

#5) Cucumber Data Tables

Cucumber has the feature to support data-driven testing, which allows us to automatically run a test case multiple times with different input and validation values for a given script.

Cucumber supports the data table. The first row is considered as the column and the rows next to it are the data for the scripts.

#6) Cucumber Transpose

This is a slight modification to the Cucumber data table. Here the first column would be considered as column and the columns next are considered as data for the scripts.

#7) Cucumber Multi Scenarios

Cucumber allows us to perform testing multiple scenarios under one feature file.

#8) Cucumber Reporting

Unlike reporting and other third-party tools where we need to do some configuration to view the reporting.

Here in Cucumber, we have built-in plugins such as pretty, JSON, HTML, XML which give us the comprehensive report of test execution.

TestNG With Cucumber

We can still execute the JUnit test cases written in Cucumber using TestNG by following:

  1. We need to add the dependencies to the Maven project.
  2. Extend the class in Runner class as AbstractTestNGCucumberTests package runner.
  3. Convert the maven project and add the package(where the runner class exists).

After that, we can run the entire Cucumber test case as TestNG and generate reports relating to the same(if we have the listeners).

In this tutorial, we will discuss 3 different Cucumber examples to cover the above concepts

Example 1

It will cover hooks, tags, annotation, background, multiple scenarios and TestNG with Cucumber.

Once the Test Environment is setup:

  • Add Eclipse Cucumber plugin in Eclipse.
  • Create a Maven project and add all the required dependencies to it and also add TestNG related dependency in Maven.
  • Create a new feature file.
  • Add the required implementation for it in the Stepdef file.
  • Now create a runner file with extends AbstractTestNGCucumberTests.
  • Convert the Maven project to TestNG and in the testng.xml add the package path of Cucumber runner class.
  • Run the TestNG.xml file.

Feature file

Feature:
As a user
I want to be able to add new clients in the system
So that I can add accounting data for that client

Background:
Given I am on Github home page
When I specify Username as “xxxxxxxxxxxxxxxxxxxx” and Password as “xxx”
And Click on SignIn button

@Smoke
    Scenario: Editing the profile
Given I click on Your Profile option
When I click on edit profile button
And Uploaded new picture
Then I should be seeing new profile picture

@Regression @Everytime
    Scenario: Create new gist
Given I click on Your Gists option
When I provide filename, description
And click on Create public gist method
Then I should be seeing the new gist

Stepdef File

package com.Multi;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.But;

import java.util.List;

import cucumber.api.PendingException;
import cucumber.api.java.it.Data;
import cucumber.runtime.ScenarioImpl;
import gherkin.formatter.model.Scenario;
import gherkin.formatter.model.ScenarioOutline;
import cucumber.api.DataTable;

import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

import cucumber.api.cli.Main;

public class Step2 {
	
	static public String sb;
	static public String sa;
	static WebDriver driver = null;
	
	@Before("@Smoke,@Regression")
    public void beforeScenario(){
        System.out.println("New scenario begins");
    }	
	
	@After("@Smoke,@Regression")
    public void afterScenario(){
        System.out.println("Scenario ends");
    
    
    }
	
@MyAnnotation
public static void myanno()
{
		System.out.println("my annot gets executed");
}
	@Given("^I am on Github home page$")
	public void i_am_on_Github_home_page(){
		String site = "https://www.github.com/login";
		System.setProperty("webdriver.chrome.driver", 
"Executables\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.navigate().to(site);
		//driver.findElement(By.cssSelector("a[contains[@href, 
"login"]]").click();
		// Write code here that turns the phrase above into concrete actions
	}
	@When("^I specify Username as \"([^\"]*)\" and Password as \"([^\"]*)\"$")
	public void i_specify_Username_as_and_Password_as(String arg1, String arg2){
		driver.findElement(By.cssSelector("input#login_field")).sendKeys(arg1);
		driver.findElement(By.cssSelector("input#password")).sendKeys(arg2);
	    // Write code here that turns the phrase above into concrete actions
	}
	@When("^Click on SignIn button$")
	public void click_on_SignIn_button(){
		driver.findElement(By.cssSelector("input.btn")).click();
	    // Write code here that turns the phrase above into concrete actions
	}
	@Given("^I click on Your Profile option$")
	public void i_click_on_Your_Profile_option(){
		driver.findElement(By.xpath("//*[@id='user
-links']/li[3]/details/summary/img")).click();
		List<WebElement> olist = driver.findElements(By.xpath("//*[@id=
'user-links']/li[3]/details/ul/li/a[@class='dropdown-item']"));
		for(WebElement o:olist)
		{
			if(o.getText().equals("Your profile"))
			{
				o.click();
				break;
			}
		}
	   
		// Write code here that turns the phrase above into concrete actions
	}
	@When("^I click on edit profile button$")
	public void i_click_on_edit_profile_button(){
		driver.findElement(By.xpath("//*[@id='js-pjax
-container']/div/div[2]/div[1]/a")).click();
	    // Write code here that turns the phrase above into concrete actions
	}

	@When("^Uploaded new picture$")
	public void uploaded_new_picture() throws InterruptedException{
		WebElement s1 = driver.findElement(By.xpath("//*[@class='avatar-upload
-container clearfix']/Img"));
		sb=s1.getAttribute("src");
		System.out.println(s1.getAttribute("src"));
		driver.findElement(By.id("upload-profile
-picture")).sendKeys("D://cucumberFinal//multiple//Files//images.jpg");
		Thread.sleep(10000);
		String wh = driver.getWindowHandle();
		driver.switchTo().window(wh);
		
		Actions actions = new Actions(driver);
	     WebElement element = driver.findElement(By.xpath("//div[@class='facebox
-content']/form/div[3]/button"));
	     Thread.sleep(10000);
	     actions.moveToElement(element);
	     //Thread.sleep(10000);
	     actions.click();
	     //actions.sendKeys("GIST1 Description");
	   actions.build().perform();
	//	driver.findElement(By.xpath("//div[@class='facebox
-content']/form/div[3]/button")).click();
		Thread.sleep(3000);
		// Write code here that turns the phrase above into concrete actions
	}

	@Then("^I should be seeing new profile picture$")
	public void i_should_be_seeing_new_profile_picture(){
		WebElement s1 = driver.findElement(By.xpath("//*[@class='avatar-upload
-container clearfix']/Img"));
		sb=s1.getAttribute("src");
		System.out.println(s1.getAttribute("src"));
		if(!(sb.equals(sa)))
		{
		Assert.assertTrue("File Upload successful", true);
		}
	    // Write code here that turns the phrase above into concrete actions
	}
	
	@Given("^I click on Your Gists option$")
	public void i_click_on_Your_Gists_option(){
		driver.findElement(By.xpath("//*[@id='user-links']/li[3]/details/summary/img")).click();
		List<WebElement> olist = driver.findElements(By.xpath("//*[@id=
'user-links']/li[3]/details/ul/li/a[@class='dropdown-item']"));
		for(WebElement o:olist)
		{
			if(o.getText().equals("Your Gists"))
			{
				o.click();
				break;
			}
		}
		// Write code here that turns the phrase above into concrete actions
	}

	@When("^I provide filename, description$")
	public void i_provide_filename_description() throws InterruptedException {
	    // Write code here that turns the phrase above into concrete actions
     driver.findElement(By.xpath("//div[@class='edit 
container']/div[@id='gists']/input")).sendKeys("Gist1");
     Thread.sleep(2000);
     Actions actions = new Actions(driver);
     WebElement element = 
driver.findElement(By.xpath("//*[@id='gists']/div[2]/div/div[2]/div/div[5]/div[1]/
div/div/div/div[5]/div/pre/span"));
     actions.moveToElement(element);
     actions.click();
     actions.sendKeys("GIST1 Description");
     actions.build().perform();
    // 
driver.findElement(By.xpath("//*[@id='gists']/div[2]/div/div[2]/div/div[5]/div[1]/
div/div/div/div[5]/div/pre/span")).sendKeys("GIST1 Description");
	Thread.sleep(2000);
	}

	@When("^click on Create public gist method$")
	public void click_on_Create_public_gist_method() {

	   driver.findElement(By.xpath("//*[@id='new_gist']/div[2]/div[2]/button[1]")).click();
		// Write code here that turns the phrase above into concrete actions
	}
	@Then("^i should be seeing the new gist$")
	public void i_should_be_seeing_the_new_gist(){
	   
		List<WebElement> glist = driver.findElements(By.xpath("//div[@class='container repohead-details-
container']/ul[1]/li[@class='flex-auto']/div/a"));
		for(WebElement o:glist)
		{
			if(o.getText().equals("Gist1"))
			{
				System.out.println("Gist created successfully");
			}
		}
		// Write code here that turns the phrase above into concrete actions
	}
}

Here is the Test Result of TestNG XML

Testng Report

The default TestNG report looks like the one given below.

Testng Default Report

Example 2

It will cover data tables and transpose.

Once the Environment is setup:

  • Add Eclipse Cucumber plugin in Eclipse.
  • Create a Maven project and add all the required dependencies to it.
  • Create a new feature file.
  • Add the required implementation for it in stepdef file.
  • Execute directly from the feature file by right-clicking on the file >> Run as >> Cucumber.feature

Feature File

Feature: Title of your feature
I want to use this template for my feature file

Background:
Given I am on Gmail login page
When I specify Username and Password
And Click on SignIn button

Scenario: Create new message from data table
When I am on New Email Page
And I specify the following details
| To1 | Subject |
| Person1@email.com | Person1 subject |
| Person2@email.com | Person2 subject |

Scenario: Create new message from transposed data table
When I am on New Email Page
And I specify following details from transpose table
| To1 | Person1@email.com | Person2@email.com |
| Subject | Person1 subject | Person2 subject |

 Stepdef file

package com.datatable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.*;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

import cucumber.api.DataTable;
import cucumber.api.Transpose;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import gherkin.formatter.model.Examples;
import cucumber.runtime.CucumberException;
import cucumber.runtime.ParameterInfo;
import cucumber.runtime.xstream.LocalizedXStreams;

public class Step3 {
	static public WebDriver driver;
	@Given("^I am on Gmail login page$")
	public void i_am_on_Gmail_login_page() throws InterruptedException{
		System.setProperty("webdriver.chrome.driver",
 "Executables/chromedriver.exe");
		driver= new ChromeDriver();
		Actions act = new Actions(driver);
		driver.manage().window().maximize();
		driver.navigate().to("https://www.google.com/gmail/about");
		driver.findElement(By.xpath("//nav/div/a[2]")).click();
		Thread.sleep(3000);
	}
	@When("^I specify Username and Password$")
	public void i_specify_Username_and_Password() throws InterruptedException{
		driver.findElement(By.xpath("//input[@type='email']")).sendKeys("xxxxxx@xxx.
com");

	    driver.findElement(By.xpath("//*[@id='identifierNext']/content/span")).click();
	    Thread.sleep(3000);
		driver.findElement(By.xpath("//input[@type='password']")).sendKeys("xxxxxxxx
xxx");
	}

	@When("^Click on SignIn button$")
	public void click_on_SignIn_button() throws InterruptedException{

		driver.findElement(By.xpath("//*[@id='passwordNext']/content/span")).click();
	   Thread.sleep(5000);
	}
	@When("^I am on New Email Page$")
	public void i_am_on_New_Email_Page(){
	}
	@When("^I specify following details$")
	public void i_specify_following_details(DataTable tables)throws Throwable{
		    for (Map<String, String> row : tables.asMaps(String.class,
 String.class))
		    {
		    	driver.findElement(By.xpath("//*[@id=':x4']/div/div")).click();
		    	//driver.switchTo().
		        System.out.println(row.get("To1"));
		        System.out.println(row.get("Subject"));
		        String whandle = driver.getWindowHandle();
		        driver.switchTo().window(whandle);

		    	driver.findElement(By.xpath("//td[@class='eV']/div[1]/div/textarea")).sendKeys
(row.get("To1"));					
		    	driver.findElement(By.xpath("//table[@class='aoP aoC
 bvf']/tbody/tr/td/form/div[3]/input")).sendKeys(row.get("Subject"));	
	
		    	driver.findElement(By.xpath("//table[@class='IZ']/tbody/tr/td/div")).click();
		   Thread.sleep(3000);
		    }
		 }
	@When("^I specify following details from transpose table$")
	public void i_specify_following_details_from_transpose_table(DataTable 
tables) throws InterruptedException {
//	    DataTable tables = null;
		for (Map<String, String> row : tables.transpose().asMaps(String.class, String.class))
	    {
	    	driver.findElement(By.xpath("//*[@id=':x4']/div/div")).click();
	    	//driver.switchTo().
	    	Thread.sleep(2000);
	        System.out.println(row.get("To1"));
	        System.out.println(row.get("Subject"));
	        String whandle = driver.getWindowHandle();
	        driver.switchTo().window(whandle);

	    	driver.findElement(By.xpath("//td[@class='eV']/div[1]/div/textarea")).sendKeys
(row.get("To1"));	
	    	Thread.sleep(3000);
	    	driver.findElement(By.xpath("//table[@class='aoP aoC 
bvf']/tbody/tr/td/form/div[3]/input")).click();
	        driver.findElement(By.xpath("//table[@class='aoP aoC 
bvf']/tbody/tr/td/form/div[3]/input")).sendKeys(row.get("Subject"));
						
	    	Thread.sleep(3000);

	        driver.findElement(By.xpath("//table[@class='IZ']/tbody/tr/td/div")).click();
	   Thread.sleep(3000);
	    }
	}
		@When("^then click on Send button$")
		public void then_click_on_Send_button(){
		    // Write code here that turns the phrase above into concrete actions
		}
		@Then("^I should be able to send the email successfully$")
		public void i_should_be_able_to_send_the_email_successfully() {
		    // Write code here that turns the phrase above into concrete actions
		}

Output: So the above example shall log in to Gmail and send two emails for each scenario that is for the Data table and Transposed Data table.

Example 3

It will cover reporting.

Once the Environment is setup:

  • Add Eclipse Cucumber plugin in Eclipse.
  • Create a Maven project and add the all required dependencies to it.
  • Create a new feature file.
  • Add the required implementation for it in the Stepdef file.
  • Create a runner class and execute the runner class.
  • View all the types of reports.

Feature file

Feature: Title of your feature
I want to use this template for my feature file

@tag1

Scenario: Title of your scenario
Given I am on Github home page
When I specify Username and Password
And Click on SignIn button
Then I should be able to see logout option

Stepdef File

package com.cucumber;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumber.api.java.en.But;

import java.util.List;

import cucumber.api.PendingException;
import cucumber.api.java.it.Data;
import cucumber.api.DataTable;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.cli.Main;

public class Step1 {
	static WebDriver driver = null;
	@Given("^I am on Github home page$")
	public void i_am_on_Github_home_page(){
		String site = "https://www.github.com/login";
		System.setProperty("webdriver.chrome.driver", "Executables\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.navigate().to(site);
		//driver.findElement(By.cssSelector("a[contains[@href, 
"login"]]").click();
		// Write code here that turns the phrase above into concrete actions
	}

	@When("^I specify Username and Password$")
	public void i_specify_Username_and_Password() {
		driver.findElement(By.cssSelector("input#login_field")).sendKeys("chintamoni
.patra@gmail.com");
		driver.findElement(By.cssSelector("input#password")).sendKeys("Test@123");
	    // Write code here that turns the phrase above into concrete actions
	}

	@When("^Click on SignIn button$")
	public void click_on_SignIn_button(){
		driver.findElement(By.cssSelector("input.btn")).click();
	    // Write code here that turns the phrase above into concrete actions
	}

	@Then("^I should be able to see logout option$")
	public void I_should_be_able_to_see_logout_option() throws InterruptedException{
		driver.findElement(By.xpath("//*[@id='user
-links']/li[3]/details/summary/img")).click();
		WebElement opt = driver.findElement(By.xpath("//*[@id='user-
links']/li[3]/details/ul/li"));
		List<WebElement> olist = 
opt.findElements(By.xpath("//li/form/button"));
		for(WebElement o : olist)
		{
		System.out.println(o);
	}
		//int a = olist.size();
		System.out.println(olist.get(0).getText());
		olist.get(0).click();
		Thread.sleep(2000);
		
	    // Write code here that turns the phrase above into concrete actions
	}

}

Here are the various types of Reports that are generated by Cucumber:

HTML Report

Html Report

Pretty

Pretty Report

Junit

Junit Report

Conclusion

Being an open-source tool, Cucumber is widely used in BDD. And it is very easy to understand and it has a lot of scope with respect to new features and it is practically possible to integrate Cucumber with Selenium or any other third party tools/jars etc.

As it has active help groups/members it really becomes easy for anyone who has just started learning Cucumber or for those who are having intermediate knowledge in Cucumber/BDD.

Cucumber further supports integration with the excel sheet and Jenkins as well.

Was this helpful?

Thanks for your feedback!

Leave a Comment