Cucumber Tutorial PDF
Cucumber Tutorial PDF
Cucumber allows automation functional validation that is easily read and understood.
Cucumber was initially implemented in Ruby and then extended to Java framework. Both
the tools support native JUnit.
This tutorial is fairly comprehensive and covers all the necessary aspects on Cucumber
using examples for easy understanding.
Audience
This tutorial is designed for software professionals such as analysts, developers, and
testers who are keen on learning the fundamentals of Cucumber and want to put it into
practice.
Prerequisites
Before proceeding with this tutorial, you need to have a basic knowledge on testing as well
as some hands-on experience of some testing tools. You should have a commanding
knowledge on Java, and some familiarity with JUnit and Ruby.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
1
Cucumber
Table of Contents
About the Tutorial ................................................................................................................................... 1
Audience ................................................................................................................................................. 1
Prerequisites ........................................................................................................................................... 1
3. CUCUMBER – GHERKINS.................................................................................................... 11
4. CUCUMBER – FEATURES.................................................................................................... 13
2
Cucumber
3
1. Cucumber – Overview Cucumber
In order to get better advantage of the software testing, organizations are nowadays
taking a step forward. They implement important acceptance test scenarios while
development is in-progress. This approach is commonly known as Behavior Driven
Development (BDD).
Behavior Driven Development gives us an opportunity to create test scripts from both the
developer’s and the customer’s prospective as well. So in the beginning, developers,
project managers, QAs, user acceptance testers and the product owner (stockholder), all
get together and brainstorm about which test scenarios should be passed in order to call
this software/application successful. This way they come up with a set of test scenarios.
All these test scripts are in simple English language, so it serves the purpose of
documentation also.
Example
If we are developing a user authentication feature, then the following can be few key test
scenarios, which needs to get passed in order to call it a success.
The user should be able to login with correct username and correct password.
The user should not be able to login with incorrect username and correct password.
The user should not be able to login with correct username and incorrect password.
How it Works
By the time the code is ready, test scripts are ready too. The code has to pass the test
scripts defined in BDD. If it does not happen, code refactoring will be needed. Code gets
freezed only after successful execution of defined test scripts.
1
Cucumber
It is a very simple notion, but what we need in order to get this concept implemented. The
answer is, Behavior Driven Development (BDD) Framework. Cucumber is one such open
source tool, which supports behavior driven development. To be more precise, Cucumber
can be defined as a testing framework, driven by plain English text. It serves as
documentation, automated tests, and a development aid – all in one.
Cucumber reads the code written in plain English text (Language Gherkin – to be
introduced later in this tutorial) in the feature file (to be introduced later).
It finds the exact match of each step in the step definition (a code file - details provided
later in the tutorial).
The piece of code to be executed can be different software frameworks like Selenium,
Ruby on Rails, etc. Not every BDD framework tool supports every tool.
This has become the reason for Cucumber's popularity over other frameworks, like
JBehave, JDave, Easyb, etc.
Ruby on Rails
Selenium
PicoContainer
Spring Framework
Watir
It acts as a bridge between the business and technical language. We can accomplish
this by creating a test case in plain English text.
It allows the test script to be written without knowledge of any code, it allows the
involvement of non-programmers as well.
2
2. Cucumber – Environment Cucumber
In this chapter, we will see the environment setup for Cucumber with Selenium WebDriver
and Java, on Windows Machine.
Java
Why we need: Java is a robust programming language. Cucumber supports Java
platform for the execution.
How to install:
Step (1): Download jdk and jre from the following link
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Step (4): Set the environment variable as shown in the following screenshots.
3
Cucumber
4
Cucumber
Eclipse
How to install:
Maven
Why we need: Maven is a build automation tool used primarily for Java projects.
It provides a common platform to perform activities like generating source code,
compiling code, packaging code to a jar, etc. Later if any of the software versions
gets changed, Maven provides an easy way to modify the test project
accordingly.
5
Cucumber
How to install:
Step (4): Edit Path variable and include Maven as shown in the following
screenshot.
Step (7): Go to Help -> Eclipse Marketplace -> Search Maven -> Maven
Integration for Eclipse -> INSTALL.
Go to File -> New -> Others -> Maven -> Maven Project -> Next.
Provide group Id (group Id will identify your project uniquely across all projects).
6
Cucumber
Provide artifact Id (artifact Id is the name of the jar without version. You can choose
any name, which is in lowercase). Click on Finish.
Step (3): Add dependency for selenium: This will indicate Maven which Selenium jar files
are to be downloaded from the central repository to the local repository.
7
Cucumber
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.47.1</version>
</dependency>
Step (4): Add dependency for Cucumber-Java: This will indicate Maven, which Cucumber
files are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Step (5): Add dependency for Cucumber-JUnit: This will indicate Maven, which Cucumber
JUnit files are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
8
Cucumber
Step (6): Add dependency for JUnit: This will indicate Maven, which JUnit files are to be
downloaded from the central repository to the local repository.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
You will be able to see a Maven repository like shown in the following screenshot.
9
Cucumber
10
3. Cucumber – Gherkins Cucumber
So far, we have got an understanding of Cucumber and what it does. It executes the test
scripts, which have been defined in the feature file (to be covered in subsequent chapters).
The language, in which this executable feature files is written, is known as Gherkin.
Gherkin is a plain English text language, which helps the tool - Cucumber to interpret and
execute the test scripts.
One may think that, it has been discussed many times that Cucumber supports simple
English text then why we need a separate language - Gherkins. The answer lies in the
concept of the Behavior Driven Development.
As discussed earlier, we had seen that BDD incorporates different prospectives while
creating test scripts. It can be development prospective, business prospective, etc. That
said, we will need people from different community like developers, project managers,
product owners, and testers while developing test scripts. As these people do not belong
to the same category, there is a risk of not using the common language for test script
conceptualizing. This was the evolution point for Gherkins.
Gherkin provides the common set of keywords in English text, which can be used by people
amongst the different community and yet get the same output in the form of test scripts.
Example
Feature: Login functionality for a social networking site. Given I am a social networking
site user. When I enter username as username1. And I enter password as password1.
Then I should be redirected to the home page of the site.
The above-mentioned scenario is of a feature called user login. All the words highlighted
in bold are Gherkin keywords.
Background
But
*
Scenario Outline
Examples
Gherkin will parse each step written in step definition file (to be covered later). So the
steps mentioned in the feature file and the step definition file (to be covered later)
should match.
11
Cucumber
You can locate the Gherkin jars in the Maven Dependency folder in the Package Explorer.
It gets downloaded along with the other Cucumber jars. It will look like the following
screenshot:
Another interesting fact about Gherkin is, it supports not only English but many other
native languages such as French, Finnish, Indonesian, Hungarian, Hindi, Urdu, Gujarati,
etc.
12
4. Cucumber – Features Cucumber
Create and remove the user from the social networking site.
User login functionality for the social networking site.
Sharing photos or videos on the social networking site.
Sending a friend request.
Logout.
By now, it is clear that, each independent functionality of the product under test can be
termed as a feature when we talk about Cucumber. It is a best practice later when you
start testing, that before deriving the test scripts, we should determine the features to be
tested.
A feature usually contains a list of scenarios to be tested for that feature. A file in which
we store features, description about the features and scenarios to be tested is known as
Feature File. We will see more about feature files in the following chapter.
The keyword to represent a feature under test in Gherkins is “Feature”. The suggested
best practice is, to write a small description of the feature beneath the feature title in the
feature file. This will fulfill the need of a good documentation as well.
Example
Feature: Login functionality for a social networking site.
The user should be able to login into the social networking site if the username and the
password are correct.
The user should be shown the error message if the username and the password are
incorrect.
The user should be navigated to home page, if the username and password are correct.
Feature Files
The file, in which Cucumber tests are written, is known as feature files. It is advisable
that there should be a separate feature file, for each feature under test. The extension of
the feature file needs to be “.feature”.
One can create as many feature files as needed. To have an organized structure, each
feature should have one feature file.
13
Cucumber
For Example:
The naming convention to be used for feature name, feature file name depends on the
individual’s choice. There is no ground rule in Cucumber about names.
Example
The given user navigates to Facebook. When I enter Username as "<username>" and
Password as "<password>". Then, login should be unsuccessful.
|username |password |
|username1 |password1 |
* AND keyword is used to show conjunction between two conditions. AND can be used
with any other keywords like GIVEN, WHEN and THEN.
14
Cucumber
Steps Definitions
We have got our feature file ready with the test scenarios defined. However, this is not
the complete job done. Cucumber doesn’t really know which piece of code is to be executed
for any specific scenario outlined in a feature file.
This calls the need of an intermediate – Step Definition file. Steps definition file stores the
mapping between each step of the scenario defined in the feature file with a code of
function to be executed.
So, now when Cucumber executes a step of the scenario mentioned in the feature file, it
scans the step definition file and figures out which function is to be called.
driver.close();
}
So with each function, whatever code you want to execute with each test step (i.e.
GIVEN/THEN/WHEN), you can write it within Step Definition file. Make sure that
code/function has been defined for each of the steps.
This function can be Java functions, where we can use both Java and Selenium commands
in order to automate our test steps.
15
5. Cucumber – Scenarios Cucumber
Scenario is one of the core Gherkin structures. Every scenario starts with the keyword
“Scenario:” (or localized one) and is followed by an optional scenario title. Each feature
can have one or more scenarios and every scenario consists of one or more steps. A very
simple example of scenario can be:
Consider a case, where we need to execute a test scenario more than once. Suppose, we
need to make sure that the login functionality is working for all types of subscription
holders. That requires execution of login functionality scenario multiple times. Copy paste
the same steps in order to just re-execute the code, does not seem to be a smart idea.
For this, Gherkin provides one more structure, which is scenario outline.
Scenario outline is similar to scenario structure; the only difference is the provision of
multiple inputs. As you can see in the following example, the test case remains the same
and non-repeatable. At the bottom we have provided multiple input values for the variables
“Username” and “Password”. While running the actual test, Cucumber will replace the
variable with input values provided and it will execute the test. Once pass-1 has been
executed, the test will rerun for second iteration with another input value. Such variable
or placeholders can be represented with ”<>” while mentioning with gherkin statements.
Example
When the user logs in using the Username as "<username>" and the Password as
"<password>", then login should be successful.
|username |password |
|user1 |password1 |
|user2 |password2 |
There are a few tips and tricks to smartly define the Cucumber scenarios.
Each step should be clearly defined, so that it does not create any confusion for the
reader.
Do not repeat the test scenario, if needed use scenario outline to implement
repetition.
16
Cucumber
Develop a test step in a way that, it can be used within multiple scenarios and
scenario outlines.
As far as possible, keep each step completely independent. For example: “Given
the user is logged in”. This can be divided into two steps:
17
6. Cucumber – Annotations Cucumber
Given:
o It describes the pre-requisite for the test to be executed.
o Example:
GIVEN I am a Facebook user
When:
o It defines the trigger point for any test scenario execution.
o Example: WHEN I enter "<username>"
Then
o Then holds the expected result for the test to be executed.
o Example: THEN login should be successful.
And:
o It provides the logical AND condition between any two statements. AND can
be used in conjunction with GIVEN, WHEN and THEN statement.
But:
o It signifies logical OR condition between any two statements. OR can be
used in conjunction with GIVEN, WHEN and THEN statement.
o Example: THEN login should be successful. BUT home page should not be
missing.
Scenario:
o Details about the scenario under the test needs to be captured after the
keyword “Scenario:”
o Example:
Scenario:
GIVEN I am a Facebook user
WHEN I enter my
AND I enter my
THEN login should be successful.
BUT home page should not be missing.
o Example:
Background:
Go to Facebook home page.
Example Scenario
Let’s automate a scenario in order to understand annotations better.
Step 1
Create a Maven Test Project named as AnnotationTest.
Go to File -> New -> Others -> Maven -> Maven Project -> Next.
Provide group Id (group Id will identify your project uniquely across all projects).
Provide artifact Id (artifact Id is the name of the jar without version. You can choose
any name which is in lowercase).
Click on Finish.
Open pom.xml:
o Go to package explorer on the left hand side of Eclipse.
Add dependency for Selenium: This will indicate Maven, which Selenium jar files
are to be downloaded from the central repository to the local repository.
19
Cucumber
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.47.1</version>
</dependency>
Add dependency for Cucumber-Java: This will indicate Maven, which Cucumber files
are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Add dependency for Cucumber-JUnit: This will indicate Maven, which Cucumber
JUnit files are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Add dependency for JUnit: This will indicate Maven, which JUnit files are to be
downloaded from the central repository to the local repository.
20
Cucumber
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
Verify binaries.
o Once pom.xml is edited successfully, save it.
Step 2
Step 3
21
Cucumber
Feature: annotation
Step 4
package Annotation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
22
Cucumber
driver.close();
}
@Then("^Relogin option should be available$")
public void checkRelogin()
{
if(driver.getCurrentUrl().equalsIgnoreCase("https://www.facebook.com/login.php?
login_attempt=1&lwv=110")){
System.out.println("Test2 Pass");
}
else {
System.out.println("Test2 Failed");
}
driver.close();
}
}
Step 5
23
Cucumber
package Annotation;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(format={"pretty", "html:target/cucumber"})
public class runTest {
}
Step 6
You will observe the following things when you run this class file:
24
7. Cucumber – Scenario Outline Cucumber
Scenario outline basically replaces variable/keywords with the value from the table. Each
row in the table is considered to be a scenario.
Let’s continue with the same example of Facebook login feature. So far we have been
executing one scenario: Upon providing the correct user name, login is successful. Now,
suppose we want to check if login is successful for all three possible types of inputs, which
are username, email address, or phone number. To achieve this, we will need to write
three different scenarios, where each scenario will vary with the type of input, login is
successful. In this case, scenarios will look like the following.
Scenario:
Given user navigates to Facebook
When I enter correct username and password
Then login should be successful
Scenario:
Given user navigates to Facebook
When I enter correct email address and password
Then login should be successful
Scenario:
Given user navigates to Facebook
When I enter correct phone number and password
Then login should be successful
Here, if we see closely, for above three scenarios: statements are the same, only the
input parameter (username/email address/phone number) is changing. That’s where the
importance of scenario outline comes into picture.
When we define any scenario with scenario outline, we can specify one test scenario and
at the bottom of it we can provide a number of inputs. The scenario will get executed as
many times as the number of inputs provided.
Example
Go to File -> New -> Others -> Maven -> Maven Project -> Next.
Provide group Id (group Id will identify your project uniquely across all projects).
Provide artifact Id (artifact Id is the name of the jar without version. You can choose
any name which is in lowercase).
25
Cucumber
Click on Finish.
Open pom.xml:
o Go to package explorer on the left hand side of Eclipse.
Add dependency for Selenium: This will indicate Maven, which Selenium jar files
are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.47.1</version>
</dependency>
Add dependency for Cucumber-Java: This will indicate Maven, which Cucumber files
are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
26
Cucumber
Add dependency for Cucumber-JUnit: This will indicate Maven, which Cucumber
JUnit files are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Add dependency for JUnit - This will indicate Maven, which JUnit files are to be
downloaded from the central repository to the local repository.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
Verify binaries.
27
Cucumber
28
Cucumber
Examples:
|username |password |
|username1 |password1 |
|username2 |password2 |
Note: Here, example annotation describes the range of input to be provided upon scenario
execution. Test scenario will be executed for each of the input provided. So, in the given
example, test scenario will be executed three times.
package Outline;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
public class stepdefinition {
WebDriver driver = null;
@Given("^user navigates to facebook$")
public void goToFacebook() {
driver = new FirefoxDriver();
driver.navigate().to("https://www.facebook.com/");
}
29
Cucumber
Note: In the above code, we have to define a function having two input argument: one
username and other will be for password. So for each set of input provided in the example
tag, Set of GIVEN, WHEN and THEN will be executed.
package Outline;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(format={"pretty", "html:target/cucumber"})
public class runTest {
}
You will observe the following things when you run this class file:
In nutshell, when scenario does not change but only the data value gets changed, it is
advisable to use scenario outline data tables.
30
8. Cucumber – Tags Cucumber
It looks simple when we just have one, two, or maybe five scenarios in a feature file.
However, in real life it does not happen. For each feature under test, we may have 10, 20,
or may be more number of scenarios in a single feature file. They may represent different
purpose (Smoke test/Regression test), different prospectives (Developer/QA/BA),
different status (Ready for execution/Work in progress), etc. How to manage execution
for such a mass?
For this, Cucumber has already provided a way to organize your scenario execution by
using tags in feature file. We can define each scenario with a useful tag. Later, in the
runner file, we can decide which specific tag (and so as the scenario(s)) we want Cucumber
to execute. Tag starts with “@”. After “@” you can have any relevant text to define your
tag. Let’s understand this with an example.
Suppose, there are two or more scenarios in a feature file. We want to execute only one
scenario as part of smoke test. So first thing is to identify that scenario and second is to
tag it with “@SmokeTest” text at the beginning of the scenario.
Let’s take a deep look at it:
Write the following text within the file and save it. This feature file contains two
scenarios where only one has been marked as SmokeTest tag.
Examples:
|username |password |
|username1 |password1 |
|username2 |password2 |
31
Cucumber
#following scenario has been tagged as SmokeTest and this should get executed.
@SmokeTest
Scenario:
Given user navigates to Facebook
When I enter Username as "<>" and Password as "<>"
Then the user should be redirected to login retry
package cucumberTag;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
32
Cucumber
driver.close();
}
@Then("^User should be redirected to login retry$")
public void loginRetry() {
if(driver.getCurrentUrl().equalsIgnoreCase("https://www.facebook.com/login.php?
login_attempt=1&lwv=110")){
System.out.println("Test Pass");
}
else {
System.out.println("Test Failed");
}
driver.close();
}
}
package cucumberTag;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(format={"pretty", "html:target/cucumber"})
public class runTest {
}
You will observe the following things, when you run this class file.
There is no limit in defining tags within the feature file. Based on your need, you can derive
tags to be used and scenarios to be executed.
33
Cucumber
Tag can also be defined at a feature level. Once you define a tag at the feature level, it
ensures that all the scenarios within that feature file inherits that tag.
Depending on the nature of the scenario, we can use more than one tag for the single
feature. Whenever Cucumber finds an appropriate call, a specific scenario will be executed.
Cucumber also provides a way to inverse the choice of tags. Consider that out of 25 defined
scenarios, 10 are marked as smoke test. We are required to execute only regression test
scenarios.
For this, we can use “~” in JUnit runner class to exclude smoke test scenario. It will look
like the following.
@RunWith(Cucumber.class)
@Cucumber.Options(format={"pretty",
"html:target/cucumber"},tags={"~@SmokeTest"})
public class runTest {
}
While defining multiple tags, we can also define logical or/and logical and operation.
34
9. Cucumber – Data Tables Cucumber
While working on automation, we may face variety of scenarios. Each scenario carries a
different meaning and needs.
Since the beginning, we have been taking an example of login functionality for a social
networking site, where we just had two input parameters to be passed. Let’s think of some
more possibility. How about “New user registration” functionality? Typically, what can be
the input parameters while registering a new user for a social networking site? Something
like the following:
User Name
Email Address
Password
Re-enter password
Birthdate
Gender
Phone number
It looks a bit messy at first glance. So, is there any better way to manage such chunk of
inputs? Answer can be “Data Table”. Data table is a set of input to be provided for a
single tag. This tag can be GIVEN, WHEN, or THEN.
Let’s write the above scenario with the help of data table and it will look like the following:
| Fields | Values |
| First Name | Tom |
| Last Name | Kenny |
| Email Address | someone@someone.com |
| Re-enter Email Address | someone@someone.com |
| Password | Password1 |
| Birthdate | 01 |
35
Cucumber
Example
Go to File -> New -> Others -> Maven -> Maven Project -> Next.
Provide group Id (group Id will identify your project uniquely across all projects).
Provide artifact Id (artifact Id is the name of the jar without version. You can
choose any name which is in lowercase).
Click on Finish.
Open pom.xml:
o Go to package explorer on the left hand side of Eclipse.
o Expand the project CucumberTest.
o Locate pom.xml file.
o Right-click and select the option, Open with “Text Editor”
Add dependency for Selenium: This will indicate Maven, which Selenium jar files
are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.47.1</version>
</dependency>
Add dependency for Cucumber-Java: This will indicate Maven, which Cucumber files
are to be downloaded from the central repository to the local repository.
36
Cucumber
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Add dependency for Cucumber-JUnit: This will indicate Maven, which Cucumber
JUnit files are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Add dependency for JUnit: This will indicate Maven, which JUnit files are to be
downloaded from the central repository to the local repository.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
Verify binaries.
o Once pom.xml is edited successfully, save it.
o Go to Project ->Clean: It will take a few minutes.
37
Cucumber
Verify that the new user registration is unsuccessful after passing incorrect
inputs.
Scenario:
Given I am on the new user registration page
When I enter invalid data on the page
| Fields | Values |
| First Name | Tom |
| Last Name | Kenny |
| Email Address | someone@someone.com |
| Re-enter Email Address | someone@someone.com |
| Password | Password1 |
| Birthdate | 01 |
Create the step definition file named as ‘dataTable.java’ inside the package
dataTable (see section scenario outline for more detailed steps).
package dataTable;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
38
Cucumber
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.table.DataTable;
//Enter data
driver.findElement(By.name("firstname")).sendKeys(data.get(1).get(1));
driver.findElement(By.name("lastname")).sendKeys(data.get(2).get(1));
driver.findElement(By.name("reg_email__")).sendKeys(data.get(3).get(1));
driver.findElement(By.name("reg_email_confirmation__")).sendKeys(data.get(4).get(1));
driver.findElement(By.name("reg_passwd__")).sendKeys(data.get(5).get(1));
driver.findElement(By.className("_58mt")).click();
if(driver.getCurrentUrl().equalsIgnoreCase("https://www.facebook.com/")){
System.out.println("Test Pass");
}
39
Cucumber
else {
System.out.println("Test Failed");
}
driver.close();
}
}
package dataTable;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(format={"pretty", "html:target/cucumber"})
public class runTest {
}
We will see that home page will not displayed and “Test Pass” will be written on
the console.
40
10. Cucumber – Comments Cucumber
Comment is basically a piece of code meant for documentation purpose and not for
execution. Be it a step definition file or a feature file, to make it more readable and
understandable. So, it is important to use/put comments at appropriate places in the file.
This also helps while debugging the code. Cucumber feature files can have comments at
any place. To put comments, we just need to start the statement with “#” sign.
Different programming languages have got different norms for defining the comments.
Let’s see how Cucumber deals with it.
Step definition file: If you are using Java as a platform then mark your comments
with “//”.
Feature File: In case of feature file, we just need to put # before beginning your
comment.
Example
The highlighted text in the program refer to the comments in the code.
Feature: annotation
41
11. Cucumber – Hooks Cucumber
Cucumber hook allows us to better manage the code workflow and helps us to reduce
the code redundancy. We can say that it is an unseen step, which allows us to perform
our scenarios or tests.
To understand this notion better, let’s take an example of a feature file and a step
definition file.
The highlighted portion in the given statement actually does the job of setting up the
webdriver and ending the webdriver session. So, it is actually not relevant to the essence
of “Given statement”, and it is more like a setup for the test. Also if we think with a broader
prospective, then in case of multiple scenarios for this feature, this webdriver setup and
cleanup will run with each given statement. Logically, it makes sense to have the setup
and cleanup executed only once.
So to bring optimization, hooks can be utilized. More often we use two types of hooks:
“Before” hook and “After” hook. Method/function/piece of code, defined within Before and
After hooks, always run, even if the scenario gets passed or failed.
As the name suggests, before hook gets executed well before any other test scenarios,
and after hook gets executed after executing all the scenarios.
Step (1): Create Maven project as hookTest, add necessary dependency in pom.xml.
Step (3): Create a step definition file named as hookTest.java under the package.
package hookTest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
42
Cucumber
driver.close();
}
@After
public void cleanUp(){
driver.close();
}
}
Step (4): Create a feature file named “hookTest.feature” under the package.
Examples:
|username |password |
|username1 |password1 |
43
Cucumber
Create the runner class as runTest.java inside the package dataTable (see the
section scenario outline for more detailed steps).
package hookTest;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(format={"pretty", "html:target/cucumber"})
public class runTest {
}
Before hook: Set up the webdriver and other prerequisites to run the test.
Given statement
When statement
Then statement
After hook: Close the webdriver and do the cleanup process.
Tagged Hooks
We can also indicate if we want before and after hooks to be executed with a specific tag
only. Example: @Before(‘@Web’). The same concept of tag logical and/or can be applied
with hooks as well. Example: @Before(@dev,@wip), @Before(@dev,~@wip)
44
12. Cucumber – Command Line Options Cucumber
Cucumber can be used to test almost any computer system. So far we have seen how to
run a test using Eclipse IDE. There is one more way through which we can run the
Cucumber test that is through command line interface. So what is the advantage of doing
it?
Running any test framework from the Terminal has its own advantages, such as overriding
the run configurations mentioned in the code.
In order to execute Cucumber test with command prompt, use the following steps after
system configuration.
Go to File -> New -> Others -> Maven -> Maven Project -> Next.
Provide group Id (group Id will identify your project uniquely across all projects).
Provide artifact Id (artifact Id is the name of the jar without version. You can choose
any name which is in lowercase).
Click on Finish.
Open pom.xml:
o Go to the package explorer on the left hand side of Eclipse.
o Expand the project CucumberTest.
o Locate pom.xml file.
o Right-click and select the option, Open with “Text Editor”.
Add dependency for Selenium: This will indicate Maven, which Selenium jar files
are to be downloaded from the central repository to the local repository.
45
Cucumber
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.47.1</version>
</dependency>
Add dependency for Cucumber-Java: This will indicate Maven, which Cucumber files
are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.0.2</version>
<scope>test</scope> </dependency>
Add dependency for Cucumber-JUnit: This will indicate Maven, which Cucumber
JUnit files are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Add dependency for JUnit: This will indicate Maven, which JUnit files are to be
downloaded from the central repository to the local repository.
46
Cucumber
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
Verify binaries.
Examples:
|username |password |
|username1 |password1 |
|username2 |password2 |
Note: Here, example annotation describes the range of input to be provided upon scenario
execution. Test scenario will be executed for each of the input provided. So, in the given
example, test scenario will be executed three times.
47
Cucumber
package Outline;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
driver.close();
}
}
Note: In code, we have to define a function having two input arguments: one username
and other will be for password. So, for each set of input provided in the example tag, set
of GIVEN, WHEN and THEN will be executed.
48
Cucumber
Write the following text within the file and save it.
package Outline;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(format={"pretty", "html:target/cucumber"})
public class runTest {
}
Run the command mvn test: You will see that all the scenario, described in the
feature file have been executed (if there isn’t any error). Finally, at the bottom you
will find the following information.
Result:
This describes the total test run, along with failure if any.
The previous command runs everything as mentioned in the JUnit Runner class. However,
if we want to override the configurations mentioned in the Runner, following are the few
examples to do it.
To run the specific tags only, run the command mvn test -Dcucumber.options="--
tags @SmokeTest" on command prompt.
It will run only tags, which are marked with @SmokeTest.
49
13. Cucumber – JUnit Runner Cucumber
It is important to understand what Junit is, before we begin our discussion for Cucumber
JUnit Runner. JUnit is an open source unit testing framework for the Java programming
language. JUnit has been important in the development of test-driven development, and
is one of a family of unit testing frameworks, which is collectively known as xUnit that
originated with SUnit.
JUnit allows the developer to incrementally build test suites to measure progress
and detect unintended side effects.
JUnit shows test progress in a bar that is normally green but turns red when a test
fails.
By now, we have seen the benefits of using JUnit, but the reason we are discussing it right
now is Cucumber framework. On one hand, Cucumber is providing a way for non-technical
person to define test cases for a product, and on the other hand, our expectation is for
smooth and timely execution of such test cases.
JUnit acts as a bridge between these two. So, the flow of execution will look like the
following:
o It will execute the functions written in the step definition file according to
feature file statements.
o It will build the test report in the specified format (which can be html/JSON).
50
Cucumber
The important point here is how to configure JUnit to do all these things? Following are
the steps:
51
Cucumber
How to install:
o Make sure JAVA is installed on your machine.
o Download Eclipse from http://www.eclipse.org/downloads.
o Unzip and Eclipse is installed.
Why we need: Maven is a build automation tool used primarily for Java projects.
It provides a common platform to perform activities like generating source code,
compiling code, packaging code to a jar, etc. Also later if any of the software
versions gets changed, Maven provides an easy way to modify the test project
accordingly.
How to install:
o Download Maven: https://maven.apache.org/download.cgi
o Edit Path variable and include Maven as shown in the following screenshot.
52
Cucumber
o Got to Help -> Eclipse Marketplace -> Search maven -> Maven Integration for
Eclipse ->INSTALL.
o Provide group Id (group Id will identify your project uniquely across all
projects).
o Provide artifact Id (artifact Id is the name of the jar without version. You can
choose any name which is in lowercase).
o Click on Finish.
53
Cucumber
Open pom.xml
o Go to package explorer on the left hand side of Eclipse.
Add dependency for Selenium: This will indicate Maven, which Selenium jar files
are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.47.1</version>
</dependency>
Add dependency for Cucumber-Java: This will indicate Maven, which Cucumber files
to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
54
Cucumber
Add dependency for Cucumber-JUnit: This will indicate Maven, which Cucumber
JUnit files are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Add dependency for JUnit: This will indicate Maven, which JUnit files are to be
downloaded from the central repository to the local repository.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
Verify binaries.
o Once pom.xml is edited successfully, save it.
o After that you will be able to see a Maven repository like the following
screenshot.
55
Cucumber
Step (7): Create Junit runner to run the test (to be covered later).
56
14. Cucumber – Reports Cucumber
In order to achieve this, we need to integrate Cucumber with other open source tool like
Ant/Junit. Here, we will take examples of JUnit further because, it provides support for
Java language.
Let’s look into the details of different report format, which is available and easy to use:
Local Directory: We can specify target directory for report as any local directory
of the machine where the test will run.
Example
Let’s automate an example of a pretty format.
Write the following text within the file and save it.
Feature: Cucumber Report
Note: Here scenario first will pass, whereas the second scenario will fail. So that we can
witness how the pass and failed report looks like.
package CucumberReport;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
if(driver.findElement(By.id("u_0_v")).isEnabled())
{
System.out.println("Test 1 Pass");
}
else
{
System.out.println("Test 1 Fail");}}
@Then("^Forgot password link should exist$")
public void forgotPWD() {
if(driver.findElement(By.id("")).isEnabled())
{
System.out.println("Test 1 Pass");
}
else
{System.out.println("Test 1 Fail");}
}
}
58
Cucumber
package CucumberReport;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(
format={"pretty", "html:target/Destination"}
)
//Specifying pretty as a format option ensure that HTML report will be
generated.
//When we specify html:target/Destination - It will generate the HTML report
inside the Destination folder, in the target folder of the maven project.
public class runTest {
You will observe the following things when you run this class file.
It exactly highlights the color of failed scenario. Moreover, you will see highlight for
failed step in that scenario. This makes the debugging very easy.
JSON Report
By now we have seen how easy HTML report is. However, if we want to pass on this report
information to any other application, that’s kind of tricky in case of HTML reports. Here
comes the need of another reporting format. JSON-Java script object notation is another
format for generating Cucumber test reports. JSON is an object containing a lot of
information stored in text format. JSON reports bring a different value to the table. JSON
report can also be used as a payload of information to be transferred between different
servers. Further, it can be used to be displayed as a web page. In a nutshell, JSON reports
can be used by other application.
What is payload information? When data is sent over the Internet, each unit
transmitted includes both header information and the actual data being sent. The header
identifies the source and destination of the packet, while the actual data is referred to as
the payload. In order to generate a JSON report, we just need to make a change in the
runner file.
package CucumberReport;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(
format={"json:target/Destination/cucumber.json"})
//When we specify json:target/Destination/cucumber.json - It will generate the
JSON report inside the Destination folder, in the target folder of the maven
project.
public class runTest {
60
Cucumber
You will observe the following things when you run this class file.
The report will be there named as cucumber.json (as provided in runner class).
You will see the report mentioned in the following screenshot after placing line
breaks:
61
15. Cucumber – Debugging Cucumber
It is very likely that your test may fail due to unknown reasons. Identifying the cause of
failure and correcting it is very important. This process is known as debugging. Following
are a few tips and tricks, which makes Cucumber debugging a bit easy.
Debugging option is available with Eclipse. Place the break point. Click the file and debug
using the following steps:
Step (1): Place the manual break points in the Ruby step definition file.
Example
require 'ruby-debug'
Then /^the process should exit cleanly$/ do
breakpoint
assert @exited_cleanly, "Process did not exit cleanly: #{@stdout}"
end
Step (2): We can also define a separate debug step like the following in the step
definition file.
Step (3): Webrat is the default tool for cucumber testing with Rails. It lets you do things
like click links, type and submit forms, and so on.
There will be times where you try to click on something, for example, and it’s not there.
You’ll get a big blob of HTML thrown back, and figuring out what that exactly means can
be a real drag.
save_and_open_page
Webrat provides a method save_and_open_page which captures the current HTML, saves
it, and then will open it in a browser for you. Extremely useful.
62
16. Cucumber – Java Testing Cucumber
63
Cucumber
o Got to Help -> Eclipse Marketplace -> Search maven -> Maven Integration for
Eclipse ->INSTALL
o Provide group Id (group Id will identify your project uniquely across all
projects).
o Provide artifact Id (artifact Id is the name of the jar without version. You can
choose any name which is in lowercase).
o Click on Finish.
64
Cucumber
Step (6): Add dependency for Selenium: This will indicate Maven, which Selenium jar
files are to be downloaded from the central repository to the local repository.
65
Cucumber
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.47.1</version>
</dependency>
Step (7): Add dependency for Cucumber-Java: This will indicate Maven, which
Cucumber files are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Step (8): Add dependency for Cucumber-JUnit: This will indicate Maven, which Cucumber
JUnit files are to be downloaded from the central repository to the local repository.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
66
Cucumber
Step (9): Add dependency for JUnit: This will indicate Maven, which JUnit files are to be
downloaded from the central repository to the local repository.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependency>
Feature:CucumberJava
67
Cucumber
package CucumberJava;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
if(driver.findElement(By.id("u_0_v")).isEnabled())
{
System.out.println("Test 1 Pass");
}
else
{
System.out.println("Test 1 Fail");
}
driver.close();
}
}
68
Cucumber
package cucumberJava;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(format={"pretty", "html:target/cucumber"})
public class runTest {
}
In the JUnit window, you will see a scenario with green tick mark, which indicates
success of the test execution.
69
17. Cucumber – Ruby Testing Cucumber
It is easy to understand.
It is an object-oriented language.
It is a powerful class library.
It has massive online support.
70
Cucumber
Download the Devkit version best suited for your operating system (i.e. 32 or 64
bit).
Next, install the gems you need for Cucumber web testing.
Run Cucumber:
C:\Users\Admin\Documents>cucumber –init
C:\Users\Admin\Documents>cucumber
71
Cucumber
Step (5): Install Watir: Go to command prompt and run the following command, "gem
install watir"
Step (6): Install rspec: Go to command prompt and run the following command, "gem
install rspec"
require "watir-webdriver"
require "rspec/expectations"
require "rubygems"
require "test/unit"
require "watir-webdriver"
def teardown
@browser.close
end
def test_search
@browser.goto "google.com"
@browser.text_field(:name => "q").set "watir"
@browser.button.click
@browser.div(:id => "resultStats").wait_until_present
assert @browser.title == "watir - Google Search"
end
end
Go to command prompt.
Go to directory e:\WithRuby
Run the following command.
73
Cucumber
74