KEMBAR78
Cucumber | PDF | Test Driven Development | Software Testing
0% found this document useful (0 votes)
42 views36 pages

Cucumber

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views36 pages

Cucumber

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

https://www.toolsqa.

com/cucumber-tutorial/

https://www.interviewbit.com/cucumber-interview-questions/

https://www.guru99.com/cucumber-interview-questions.html

https://www.javatpoint.com/cucumber-interview-questions

https://www.softwaretestinghelp.com/cucumber-interview-questions/

Cucumber BDD with examples :


https://www.softwaretestinghelp.com/cucumber-bdd-tutorial/ -

https://automationrhapsody.com/introduction-to-cucumber-and-bdd-with-examples/

https://www.softwaretestinghelp.com/selenium-webdriver-cucumber-selenium-tutorial-31/

BDD :

Behavior driven development is a process where the behaviour of the application will be described in
such a way that even non technical people like business stakeholders can easily understand it.

It is an enhancement of TDD where Test cases will be written first , and then write the functionality
based on the test cases , so that we will achieve good test coverage.

Cucumber is BDD testing tool, which is used for writing all kinds of test cases especially acceptance test
case in BDD style. It supports Gherkin.

Gherkin is a language used to write the test cases in simple format and can also be read and modified by
even no technical people

What You Will Learn: [hide]


 Background Of BDD
 Benefits Of Behavior Driven Development(BDD)
 BDD Tools
 Why Cucumber?
 How Does Cucumber Work?
 Environmental Settings
 Writing Test Cases Using Cucumber
 Creating Files For Cucumber
 Cucumber Features
o #1) Cucumber Hooks
o #2) Cucumber Tags
o #3) Cucumber Annotations
o #4) Cucumber Background
o #5) Cucumber Data Tables
o #6) Cucumber Transpose
o #7) Cucumber Multi Scenarios
o #8) Cucumber Reporting
 TestNG With Cucumber
 Conclusion
 Recommended Reading
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.

JBEHAVE CUCUMBER

Supports stories Supports Features

Very good documentation No standard documentation

Supports composite steps Does not support composite steps


JBEHAVE CUCUMBER

Not so flexible Flexible in passing parameters

Does not support background Supports background

Not so extensive reports Better formatting flexibility, built-in reports

Supports external data sources It does not support external data sources

Developed using Java Developed 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/XMLSch

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-

<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/cucu

results.xml"},

dryRun = false,

monochrome = true,

tags={"@Smoke,@Regression"}

)
Usage of Cucumber Options which we use in TestRunner File

TestRunner File is used to build a Communication between Feature File


StepDefinition Files.

features: We use Cucumber features option to define path of feature file(s).

glue: We use Cucumber glue option to define path of step definition file(s).

format: We use Cucumber format option to generate output or test results in different types of formats.
Eg: HTML Report, JUnit or TestNG Report, Cucumber Report and So.

monochrome: We use Cucumber monochrome option to print console output in a very readable format.
monochrome must be set to true in order to achieve it.

strict: We use Cucumber strict option to check if any step if not defined in step definition file.
If any step is not defined in step definition file then it will stop an execution of program.

dryRun: We use Cucumber dryRun option to check whether all the steps from feature files has got methods and imp
or no in Step Definition File.
Before execution of program dryRun must be set to true and we need to make sure that all steps are implemented in
Definition File.
Once we are sure that all steps are implemented then dryRun must be set to False and we should continue with Test

tags: We use Cucumber tags option when we have more number of scenarios in a single feature file which represent
purpose [Smoke, Sanity, Regression etc] in such cases we can make use tags option.
Eg: tags={ ” @ Smoke ” } >> It will pick only and only those scenarios which are tagged with Smoke in feature files.

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")).cl

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 rep

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

The default TestNG report looks like the one given below.

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")).send

(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
Pretty

Junit

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.
Recommended Reading
 Cucumber Selenium Tutorial: Cucumber Java Selenium WebDriver
Integration
 REST API Testing With Cucumber Using BDD Approach
 Automation Testing Using Cucumber Tool and Selenium – Selenium
Tutorial #30
 Cucumber Gherkin Tutorial: Automation Testing Using Gherkin
 Unix Shell Scripting Tutorial with Examples
 Selenium Find Element By Text Tutorial with Examples
 Java 'this' Keyword: Tutorial With Code Examples
 How To Run Cucumber With Jenkins: Tutorial With Examples

Cucumber examples can be found in selenium-samples-java/cucumber-parallel GitHub


repository.
Before going into details how to create tests with Cucumber first is good to do some context
introduction why this framework is created and getting more popular.

Test-driven development (TDD)


TDD (test driven development) is software development process in which developers first write
the unit tests for feature or module based on requirements and then implement the feature or
module itself. In short TDD cycle is “red > green > refactor”:

 Red – phase where tests are implemented according to requirements, but they still fail
 Green – phase where module or feature is implemented and tests pass
 Refactor – phase where a working code is made more readable and well structured

Behaviour-driven development (BDD)


BDD emerged from and extends TDD. Instead of writing unit tests from specification why not
make the specification a test itself. The main idea is that business analysts, project managers,
users or anyone without technical, but with sufficient business, knowledge can define tests.

Gherkin
BDD ideas sound very nice but actually are not so easy to put in practice. In order to make
documentation sufficient for testing, it should follow some rules. This is where Gherkin comes in
place. It is a Business Readable, Domain Specific Language created especially to describe
behavior without defining how to implement it. Gherkin serves two purposes: it is your project’s
documentation and automated tests.

Cucumber
Cucumber is not a testing tool it is a BDD tool for collaboration between all members of the
team. So if you are using Cucumber just for automated testing you can do better.
Testwise Cucumber is a framework that understands Gherkin and runs the automated tests. It
sounds like a fairy tale, you get your documentation described in Gherkin and tests just run.
Actually, it is not that simple, each step from documentation should have underlying test code
that manipulates the application and should have test conditions. All process will be described in
details with code samples below.

Setup Maven project


The proper way to do things is by using some build automation tool. Most used ones are Gradle
and Maven. Maven is more simple to use and works fine for normal workflows. Gradle can
do anything you want to do, but it comes at a price of complexity since you have to write Groovy
code for custom stuff. In order to use Cucumber-JVM (Cucumber implementation for the most
popular JVM languages: Java, Groovy, Scala, etc.) in Java 8 POM looks like this:

<properties>
<project.build.sourceEncoding>UTF-
8</project.build.sourceEncoding>
<cucumber.version>1.2.4</cucumber.version>
<selenium.version>2.48.2</selenium.version>
</properties>
<dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java8</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>${selenium.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
In order to build project in Java 8 this should be specified explicitly in POM by using maven-
compiler-plugin:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-
plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
Once the project is setup then real Cucumber usage can start.

Feature files
Everything starts with a plain text file with .feature extension written in Gherkin language that
describes only one product feature. It may contain from one to many scenarios. Below is a file
with a simple scenario for searching in Wikipedia.
Feature: search Wikipedia

Scenario: direct search article


Given Enter search term 'Cucumber'
When Do search
Then Single result is shown for 'Cucumber'
In Gherkin, each line that isn’t blank has to start with a Gherkin keyword, followed by any text
you like. The main keywords are:

 Feature
 Scenario
 Given, When, Then, And, But (Steps)
 Background
 Scenario Outline
 Examples
More information can be found in Cucumber reference page.

Don’t repeat yourself


In some features, there might be one and the same Given steps before each scenario. In order to
avoid copy/paste, it is better to define those steps as feature prerequisite
with Background keyword.
Feature: search Wikipedia

Background:
Given Open http://en.wikipedia.org
And Do login

Scenario: direct search article


Given Enter search term 'Cucumber'
When Do search
Then Single result is shown for 'Cucumber'

Data-driven testing
Cucumber makes it very easy to handle cases of different business scenarios with different input
data and different results based on that input data. The scenario is defined with Scenario
Outline. Then data is fed to this scenario with Examples table where variables are
defined with concrete values. The example below shows a scenario where a search is done for
two keywords and expected results for each is defined. It is very easy just to add more keywords
and expected result which is actually treated by Cucumber reporting as a different scenario.
Feature:

Scenario Outline:
Given Enter search term '<searchTerm>'
When Do search
Then Multiple results are shown for '<result>'

Examples:
| searchTerm | result |
| mercury | Mercury may refer to: |
| max | Max may refer to: |

Organise features and scenarios


Tags can be used in order to group feature files. A tag can be applied as annotation above
Feature or Scenario keyword in .feature file. Having correctly tagged different scenarios or
features runners can be created per each tag and run when needed. See more for tags
in Cucumber tags page.

Runners
Next step in the process is to add runners. Cucumber supports running tests with JUnit and
TestNG. In the current post, JUnit will be used. It has been imported in POM project file
with cucumber-junit. In order to run a test with JUnit a special runner class should be
created. The very basic form of the file is an empty class
with @RunWith(Cucumber.class) annotation.
import org.junit.runner.RunWith;

import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
public class RunWikipediaTest {
}
This will run the tests and JUnit results file will be generated. Although it works it is much better
to provide some Cucumber options with @CucumberOptions annotation.
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
format = {
"json:target/cucumber/wikipedia.json",
"html:target/cucumber/wikipedia.html",
"pretty"
},
tags = {"~@ignored"}
)
public class RunWikipediaTest {
}
Runner above runs all feature files which does not have tag @ignored and outputs the results
in three different formats: JSON in target/cucumber/wikipedia.json file, HTML
in target/cucumber/wikipedia.html and Pretty – a console output with colours. All formatting
options are available in Cucumber options page.

Runners strategy
Different runners can be created for different purposes. There could be runners based on specific
tags and those to be invoked in specific cases like regression and smoke testing, or full or partial
regression testing. Depends on the needs. It is possible to create runners for each feature and run
tests in parallel. There is a way to automatically generate runners and run tests in parallel. This
will speed up execution and will keep the project clean from unessential runners. More details
can be found in Running Cucumber tests in parallel post.

Runners feature file


If the runner is not linked to any feature file (no features section defined
in @CucumberOptions, like the one shown above) then runner automatically searches for
all feature files in current and all child folders.
Java package structure is represented as a folder structure. Feature files can be placed in some
package structure in resources folder of the project,
e.g. com.automationrhapsody.cucumber.parallel.tests.wikipedia. When compiled
those are copied to same folder structure in the output. So in order to run all feature files from
package above runner class need to be placed in the same package in java folder of the project.
It is possible to place the runner in parent package and it will still work as it searches all child
folders e.g com.automationrhapsody.cucumber.parallel.tests will work. Placing in a
different package will not work though,
e.g. com.automationrhapsody.cucumber.parallel.tests.other will not work. There
will be a message:
None of the features at
[classpath:com/automationrhapsody/cucumber/parallel/tests/other]
matched the filters: [~@ignored]
This means either there are no feature files
into com.automationrhapsody.cucumber.parallel.tests.other resources packag
e or those files have tag @ignored.
The easiest way is to put just one runner into default package and it will run all feature files
available. This gives more limitations than benefits in the long run though.

Running feature files without step definitions


So far feature file and the runner has been created. If now tests are started build will successes
but tests will be skipped. This is because there is no implementation available for Given, When,
Then commands in the feature file. Those should be implemented and Cucumber gives hints in
build output how to do it.

You can implement missing steps with the snippets below:

Given("^Enter search term 'Cucumber'$", () -> {


// Write code here that turns the phrase above into
concrete actions
throw new PendingException();
});

Step definitions code / glue


So far feature file has been defined with a runner for it. In terms of BDD this is OK, but in terms
of testing a step, definitions should be created so tests can actually be executed. As shown in hint
above a method with annotation @Given is needed. Annotation text is actually a regular
expression this is why it is good to start with ^ and end with $ which means the whole line from
the feature file to be matched. In order to make the step reusable, some regular expression can be
added in order to be able to pass different search terms, not only ‘Cucumber’. If there is regular
expression defined then the method can take arguments which will be actually what regex will
match in feature file text. Step definition for Given command is:
@Given("^Enter search term '(.*?)'$")
public void searchFor(String searchTerm) {
WebElement searchField =
driver.findElement(By.id("searchInput"));
searchField.sendKeys(searchTerm);
}
(.*?) is very basic regex, but it can do the work. It matches all zero or more characters
surrounded by quotes in the end of the line after “Enter search term ” text. Once matched this is
passed as argument to searchFor() method invocation.

Full step definitions for initial feature file are shown in class below:

package
com.automationrhapsody.cucumber.parallel.tests.wikipedia;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

import static junit.framework.Assert.assertTrue;


import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;

public class WikipediaSteps {

private WebDriver driver;

@Before
public void before() {
driver = new FirefoxDriver();
driver.navigate().to("http://en.wikipedia.org");
}

@After
public void after() {
driver.quit();
}

@Given("^Enter search term '(.*?)'$")


public void searchFor(String searchTerm) {
WebElement searchField =
driver.findElement(By.id("searchInput"));
searchField.sendKeys(searchTerm);
}

@When("^Do search$")
public void clickSearchButton() {
WebElement searchButton =
driver.findElement(By.id("searchButton"));
searchButton.click();
}

@Then("^Single result is shown for '(.*?)'$")


public void assertSingleResult(String searchResult) {
WebElement results = driver
.findElement(By.cssSelector("div#mw-content-
text.mw-content-ltr p"));
assertFalse(results.getText().contains(searchResult
+ " may refer to:"));

assertTrue(results.getText().startsWith(searchResult));
}
}

Before and After


As noticeable above there is method annotated with @Before. This is executed before
each scenario being run. It is used to allocate resources needed for a particular scenario to
run. It is a good idea to instantiate WebDriver into this method. @After method is run at the
end of the scenario so this is where resources are released, e.g. quitting WebDriver.

You might also like