Cucumber
Cucumber
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/
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
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 external data sources It does not support external data sources
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.
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>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.6.0</version>
</dependency>
<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>
<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>
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
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.
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.
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.
Here in Cucumber, we have built-in plugins such as pretty, JSON, HTML, XML
which give us the comprehensive report of test execution.
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;
@After("@Smoke,@Regression")
System.out.println("Scenario ends");
@MyAnnotation
System.setProperty("webdriver.chrome.driver",
"Executables\\chromedriver.exe");
driver.navigate().to(site);
//driver.findElement(By.cssSelector("a[contains[@href,
"login"]]").click();
// Write code here that turns the phrase above into concrete actions
driver.findElement(By.cssSelector("input#password")).sendKeys(arg2);
// Write code here that turns the phrase above into concrete actions
driver.findElement(By.cssSelector("input.btn")).click();
// Write code here that turns the phrase above into concrete actions
driver.findElement(By.xpath("//*[@id='user
-links']/li[3]/details/summary/img")).click();
'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
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
}
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);
-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
-container clearfix']/Img"));
sb=s1.getAttribute("src");
System.out.println(s1.getAttribute("src"));
if(!(sb.equals(sa)))
// Write code here that turns the phrase above into concrete actions
driver.findElement(By.xpath("//*[@id='user-links']/li[3]/details/summary/img")).cl
'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
// 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);
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);
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
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
The default TestNG report looks like the one given below.
Example 2
It will cover data tables and transpose.
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;
System.setProperty("webdriver.chrome.driver",
"Executables/chromedriver.exe");
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);
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$")
driver.findElement(By.xpath("//*[@id='passwordNext']/content/span")).click();
Thread.sleep(5000);
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"));
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$")
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"));
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);
// Write code here that turns the phrase above into concrete actions
}
// 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.
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;
System.setProperty("webdriver.chrome.driver", "Executables\\chromedriver.exe");
driver.navigate().to(site);
//driver.findElement(By.cssSelector("a[contains[@href,
"login"]]").click();
// Write code here that turns the phrase above into concrete actions
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
driver.findElement(By.cssSelector("input.btn")).click();
// Write code here that turns the phrase above into concrete actions
driver.findElement(By.xpath("//*[@id='user
-links']/li[3]/details/summary/img")).click();
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
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
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.
<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
Feature
Scenario
Given, When, Then, And, But (Steps)
Background
Scenario Outline
Examples
More information can be found in Cucumber reference page.
Background:
Given Open http://en.wikipedia.org
And Do login
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: |
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.
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;
@Before
public void before() {
driver = new FirefoxDriver();
driver.navigate().to("http://en.wikipedia.org");
}
@After
public void after() {
driver.quit();
}
@When("^Do search$")
public void clickSearchButton() {
WebElement searchButton =
driver.findElement(By.id("searchButton"));
searchButton.click();
}
assertTrue(results.getText().startsWith(searchResult));
}
}