You are on page 1of 44

Cucumber:

1) BDD concept was given by _____________ Dan North.

2) BDD stands for _____________. Behaviour Driven Development


3) TDD is derived from BDD. – false

4) Which of the following option is true for BDD Frameworks?


a. Increase misunderstanding
b. Reduce costs.
c. Collaborates development not business analysts
d. Focuses on business value
e. Increate cost and business value – 23
5) Tools - 12345
6) Cucumber acts as a bridge between the business and development of a
project. – true
7) Cucumber feature file is written in ________.gherkin
8) Cucumber scripting language ________________. All
9) What does CLI stands for? Not Command line interface
10) Command to install and run cucumber test is –mvn clear install
11) Cucumber dependencies needed _____ nt cucumbr –java
12) Maven is use to inject dependenc – true -1
13) Cucumber supports only on Eclipse IDE. –false
14) Cucumber dependencies needed  - all options
15) What does POM stands for ____________.proj obj model
16) Gherkin is ______________.both opns
17) Gherkins will take care of requirement. – true
18) Gherkin supports ___________60 well know
19) Feature file starts with – not Feature
20) Scenario is used in file for _____________. Not Define description
21) When is used to define ____________.event or action - 1
22) Data table is separation can be done using ___|data|
23) Description used in file for _____________.wrie descriptpon feature
24) To comment, we use _______. #
25) Feature file extension is  ______. .feature

26) Given is used to define ____________.define scene of scenario


27) Gherkin have two sections namely ______________.not features and
scenarios
28) But is used to __________.remove repetitive then
29) Command to run the Cucumber file
is _____________.@RunWith(Cucumber.class)
30) Maven command to create Java project is ____________Dartifact 3
times
31) And is used to ___________.remove rep given
32) Tag is used for ________.all the options

33) To define the random digit, _____. (\d+) will pass our random digit.
34) In our script file @Given ends with ___$
35) To get random variable ?:love
36) To match random character digit, ______________.*.
37) To differentiate between singular and plural, __________.?:

Cucumber - Course Introduction


In simple words, Cucumber can be defined as a software used by computer programmers
to perform automated acceptance testing in Behaviour Driven Development (BDD) style.

Before we delve into the features and functioning of the Cucumber tool, we'll
understand the concept of Behaviour Driven Development, commonly known as BDD.

Behaviour Driven Development


Behavior-driven development (BDD) is described as a software development technique
in which an application is defined and designed based on the way it performs.

The concept of BDD was introduced in 2003 by Dan North.

Dan North defines BDD as:

"BDD is a second-generation, outside–in, pull-based, multiple-stakeholder, multiple-scale,


high-automation, agile methodology. It describes a cycle of interactions with well-defined
outputs, resulting in the delivery of working, tested software that ma

Diving Deep into BDD


BDD is an extension of TDD (Test Driven Development). BDD uses examples to describe the
behavior of the system which is written in simple language that can be read and interpreted by
everyone in the team.

Now, let's watch this video that explains the concept of BDD with an example.

 Supports a team-centric workflow. Fine-granular requirements are derived from


team discussions giving a common understanding of the scope of the work.

 Focuses on the behavioral aspect of the system, thereby, emphasizing why a code


should be written rather than concentrating on the implementation details.
 Test cases are said to be written in a simple language which can be read and
understood by non-technical users.

Listed down are few of the benefits of using BDD:

 Collaboration: BDD helps to build a collaborative environment where the


developers, testers, business analysts, stakeholders and customers can be
involved in constructive discussions on the projects.
 Business value: BDD focus on business value. In BDD, developers have a clear
understanding of the customer expectations. Hence, features that increments
business value can be built.
 Reduce misunderstandings: Since BDD uses a common language that can be
understood by everyone in the team, it reduces the misunderstandings within the
team to a great extent.
 Reduce costs: With better understanding, there will be less rework on the code,
which will reduce the maintenance costs.

The result of BDD is happy customers and confident developers.


Now, let's evaluate how BDD becomes the best fit in Agile projects.

The following comparison shows the Agile principles (left) and how BDD achieves each of
them (right).

 Individuals and interactions: BDD involves communication and conversations.


 Working software: BDD builds software with business value.
 Customer Collaboration: BDD emphasizes collaboration with customers,
stakeholders, and team. It also helps to receive timely feedback from the
customer.
 Responding to change: BDD accepts changes through continuous
communications with the team.

Following are few of the tools that work based on the BDD concept:

 Cucumber is the most popular BDD tool, which we'll see in detail in this course.
 JBehave is a BDD tool for JAVA that is developed by Dan North.
 SpecFlow is another BDD tool similar to Cucumber, based on .Net. It is commonly
known as Cucumber for .Net.
 EasyB is a BDD framework written in Groovy.
Cucumber is an open-source, behavior-driven development (BDD) tool used for writing
automation tests in plain text (called Gherkin) that supports various software platforms
like Java, Ruby, Selenium, etc.

Originally created as a command line tool in Ruby, Cucumber has been converted to
other development environments like Java.

This course would demonstrate Cucumber with Java and JavaScript. So, let's get started!

Significance of Cucumber
Though we have several other tools that operate on the BDD concept, why should we
prefer Cucumber?

Here are the reasons for it:

 Cucumber is open source, i.e., free of cost.


 Cucumber supports several software platforms such as Ruby, .Net, Java, etc.
 Cucumber allows non-technical users to write scenarios in plain English with
minimal syntax using a language named Gherkin.
 Cucumber acts as a link between the business and technical facets of a project.
 Cucumber feature files become a living documentation and source of truth to know
the state of the project.

Source of Truth
When we talked about the advantages of Cucumber in the above card, we said
Cucumber feature files could be the source of truth for a project. But how?

Here goes the explanation:

 In BDD, the developers, testers, analysts, customer, and stakeholders will have
constructive discussions. The outcome of these discussions would be
the examples that describes the expected behavior of the system under
development.
 A team uses these examples to run as automated acceptance tests. Thus, as the
team progresses on the solution to the problem statement, using Cucumber, the
team can differentiate the examples that are implemented and those not.
Thus, it provides the source of specification and tests for the system in a single
document.

How Cucumber Works?

As mentioned in the previous cards, Cucumber acts as a link between the business and
technical facets of a project.

As shown in the figure above, the working of Cucumber can be divided into business-
facingand technology-facing.

 Business-facing will have Features, Scenarios, and Steps.


 Technology-facing has Step Definitions, Support Code, and Automation Library.

Given is the anatomy of Cucumber at a high-level. Moving ahead, we'll discuss


everything in detail.

The prerequisites for Cucumber Java installation are JDK and a set of JAR files. The
installation can be done manually or by using a build tool like Maven etc.

The execution of feature files and step definition files can either be done using
Cucumber Command Line Interface (CLI) or an IDE like Eclipse and IntelliJ.

We'll discuss both the methods in this topic.

JAR Files
Java Archive files, commonly known as JAR files have a package file format that groups
several classes, its resources, metadata, etc.

The following JAR files have to be included for the proper functioning of Cucumber :

 cucumber-core
 cucumber-java
 gherkin
 cucumber-jvm-deps

These JAR files can be downloaded from Maven repository. Go to Maven repository and
search for the JAR names.

Please ensure you download the JAR files:

 Uploaded by info.cukes.
 Latest version present in the repository.

Manually Setti ng up Cucumber in Eclipse IDE


Having discussed the prerequisites, we'll now see the steps to set up Cucumber in
Eclipse IDE.

 Create a project in Eclipse


 Add references to the Cucumber JAR files (assuming the JAR files have been downloaded
from Maven).

The first step is to build a Java project in Eclipse. (See the image above).

Adding References to JAR Files


Lastly, the Cucumber JAR files should be referenced to our Java project.

Follow these steps for the same:

1. Go to Properties of the project and select Java Build Path.


2. In the Libraries tab, add the downloaded jars as External JARs.

This will create a folder with the referenced JARs in the Eclipse project.

Now, Cucumber has been successfully set up in your Eclipse IDE.

Cucumber Eclipse Plugin


Using Cucumber Eclipse Plugin will make our jobs easier. It predefines keywords, steps,
etc. when feature files and step definitions are written. The latest version also provides
feature file templates.

Click Help -> Eclipse MarketPlace. Search for Cucumber-Eclipse and follow the steps.
5 of 12

Setting up Cucumber in Eclipse IDE Using Maven


Maven is a build automation tool used for JAVA projects.

To setup Cucumber in Eclipse IDE using Maven, the following steps should be followed.

1. Create a Maven project in Eclipse IDE.


o Every Maven project created will have a Project Object Model
(pom.xml) file.
o Go to Maven repository, search for each of the Cucumber jar files (listed in
the previous cards) and copy the XML code of it.
o In the pom.xml, under the tag <dependencies></dependencies>, add the
xml code for each of the jar file within the
tags <dependency></dependency>.
Example: cucumber-java

<dependencies>
<dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>

Run Maven
Once all the dependencies are added in pom.xml, the Maven build tool should be run to
download all the jars.

1. Go to Command Prompt.
2. Enter mvn clean install.

This will show you a BUILD SUCCESS message once the installation is completed.

Gherkin is a plain text language used to write the test cases/features/scenarios in


Cucumber, which is easily understood by everyone in the team.

It provides a light-weight structure that helps to document the examples of the behaviors


of the system based on the stakeholder's demands.

Another interesting feature of Gherkin is that it is not restricted to a single language. It


can be written in any spoken languages (around 60 of them) like Spanish, Norwegian,
French, Italian, and Arabic.

Gherkin
Before jumping directly on Gherkin, let's understand:

Why we need it?


In the development phase, there is a collaboration between the development team and
business team.
The development team consists of developer, architect, and tester.

In the business team, you have Business analysts and the Managerial team.

For a project business team will bring the requirements and provide those requirements
to the development team. Doesn't this process looks very easy but the problem starts
here.

Improve the Requirement


To handle the scenario you can give a write-up for both the cases.

 When a user logins with incorrect username or password. The application should throw an


error.
 When user logins for first-time to the application, it should suggest user to sign-up if it
doesn't find the user details.
 When the login is successful, it should talk to the homepage or if the user is a new user,
take the user to onboarding screen.

This scenario can fix your login scenarios.

Real-Time Problems
Let's talk one requirement.

Login to the application


- Enter username, password and click enter.
- The homepage is displayed.

Do you think this requirement is sufficient?

The answer is No.

What exactly are we missing here?

 Do we validate the username and password?


 If you enter the wrong password or username, what should be application response?

This information is not completely shared, but the business team will expect this from
the development team.
How to handle it?

Gherkin Structure
Feature: Login to play application

This feature is a primary action to get into Play application.

Scenario: When a user logins, with correct username and password. The user should be
directed to the Play homepage.

Given user is on the play URL https://play.fresco.me/


When the user enters credentials for laptops
Then the user is redirected to play home page.

This is how you can convert our application scenario using Gherkin.

Hope you have got some idea. You will learn more about writing scenarios
in Feature and Scenario topics.
To achieve all scenario, Gherkin was created.

Gherkin is a

 simple
 lightweight
 structured language, which is regularly spoken.

It supports more than 30 languages including English.

Gherkin Syntax
Gherkin is a line-oriented language. i.e. indentation is used to define the structure.

Following are few of the keywords used in Gherkin:

 Feature
 Background
 Scenario
 Given
 When
 Then
 And
 But
 *
 Scenario Outline
 Examples

We'll see how each of these keywords is used, as we proceed in this course.

Comments, Parameters and DataTables


Comments:

 Comments are preceded by a # character.


 Comments can be used to give additional details on the feature, scenario or steps.

Parameters:

 Parameters are enclosed within double quotes "" in the steps.

Datatables:

 Data tables can be defined for a scenario when the same steps have to be
executed for multiple data.
 The data in the Data table are separated by pipe | symbol.
 The first name in the column will be selected as the column name by default.

Example:

|Username|Password|
|User1|Pass1|
|User2|Pass2|

In the above example, the Username and Password will be taken as the column names.
This will be used for data-driven testing in Cucumber.

Language
 #language:<language code> header in the Gherkin file implies the language in which the
Gherkin file is written. By default, it takes the English language.
 Language code for Norwegian is no, for Japanese ja and so on.
 All scenarios in a feature must be written in the same language.

Feature Files
 A feature file contains the specifications in the readable language in the form of scenarios
and steps. In short, this will be our Gherkin file.
 Feature files give the information on what-to-do.
 Feature files will have a .feature extension.

Feature files use the Gherkin syntax that we discussed in the previous topic. There is no
code involved and can be understood by non-technical users too. Thus, feature files
represent the business facet of Cucumber.

Feature file has two sections:

 Feature
 Scenario

In Feature, you will write the test case topic and its description.

Feature: Login to play application


# Which is test case name.

This feature is a primary action to login into Play application.


# Description of the test case.
 A feature refers to a project functionality.
 It will be preceded by the keyword Feature.
 All feature files will start with the Feature keyword.

Example:

Feature: User login

Description
 It describes the feature in the feature file.
 Single line or multiple lines of text can be entered.
 Even though it is an optional field, this is highly recommended to improve the
understanding of the reader.
 A feature injection template can be used for writing descriptions in the feature files, as
shown below:

To meet some goal

As a type of stakeholder

I want a feature

Example:

Feature: User Login


Description:
To access the portal home page
As a user
I want a Login

 A scenario is an example that illustrates a business rule. This can be compared to


a test case in the QA perspective.
 A feature can have multiple scenarios.
 In Scenario, you will be writing the rules for execution. It should be as followed.

Scenario: When a user logins, with correct username and password. The user will be
directed to the Play homepage.
// Scenarios details.
Given User is on the play URL https://play.fresco.me/
When User enter credentials for laptops,
then User is redirected to play home page.
// Rules to be followed.

Scenario Section
As we know, Scenario defines the rule and the steps to be converted for execution.

Let's understand how to write Scenario section and use it in Java program.

Scenarios follow three steps:

 Given - It defines scene of the scenario.


 When - It defines the event or an action.
 Then - It defines expected outcome or result.

6 of 11

Given When and Then


Given

Given use to put our application in a well-known state before making any execution
process.

Note: Try to avoid writing user interaction in this step. It is a Precondition step
which must be written.
When

Using When, you can define the action to be performed.

Note: There should be only one When step.


Then

Using Then, you can verify the outcome of Whenstep.

Given When and Then


Given
Given use to put our application in a well-known state before making any execution
process.

Note: Try to avoid writing user interaction in this step. It is a Precondition step
which must be written.
When

Using When, you can define the action to be performed.

Note: There should be only one When step.


Then

Using Then, you can verify the outcome of Whenstep.

And, But
Mostly you can find multiple use of Given and Then.

Let's understand the scenario for this case.

Example:

Scenario: Sample scenario and its user of And and But


Given User is logged in
Given User did some setup
When User performs some action.
Then User should get a success message.
Then User should not see full details.

Let's rewrite the above scenario using And & But

Scenario: Sample scenario and its user of And and But


Given User is logged in
And User did some setup
When User performs some action.
Then User should get a success message.
But User should not see full details.

Repetitive Given will be replaced by And and Then will be replaced by But.


 Use of Asterisk (*)
 The steps in a scenario can also be written without using keywords. Each step can
be preceded with * an asterisk symbol.
 Example:
 Given the account balance is Rs 100
 When the user withdraws Rs 50
 Then the account balance should be Rs 50

 can be rewritten as:


 *the account balance is Rs 100
 *the user withdraw Rs 50
 *the account balance should be Rs 50

 Both the above steps execute exactly in the same way. But, from a reading
perspective, the first one is more clear. Hence, we use keywords while writing the
steps in a scenario.
 9 of 11

 Writing a Feature File


 Now, we'll write and execute a feature file.
 Can you guess the output?
 Let's wait and see!
 10 of 1


 Cucumber-JVM is used for implementing cucumber for JVM languages.
 It currently has the support of Java.
 Let's configure your system with Java, Maven, and Cucumber JVM.
 If you are familiar with Maven, then these steps will be a cake-walk for you.
However, let's try to keep it simple for your understanding.
 To create Java Project using maven.
 Use this command.
 mvn archetype:generate -DgroupId=com.play.bdd -DartifactId=cucumber-
jvm-maven -DarchetypeArtifactId=maven-archetype-quickstart
 Note:
 If you are willing to learn about Maven, please visit your Play course Maven
- Coalescing Pipeline.

Maven command will create a folder

 cucumber-jvm-maven
o src
o pom.xml

Now, you have Maven project skeleton. Let's convert this project folder for cucumber
project.

Delete an unwanted folder or file like:

 App.java file
 AppTest.java file.

$ cd src/main/java/com/play/bdd

$ rm App.jave file

Now to delete AppTest.java file.

$ cd ~

$ cd cucumber-jvm-mave/src/test/java/com/play/bdd

$ rm AppTest.java
Create a folder resources under src/test,

$ cd ~

Come out to the root directory.

$ cd cucumber-jvm-mave/src/test

Go to src/test folder

$ mkdir resources
Create resources folder
$ mkdir cucumber

Create cucumber folder.

$ vi play.feature

Under src/test, you will have two folders

1. java
2. resources


What is BDD?
 Introducing Cucumber
 Cucumber - Installation
 Gherkin Basics
 Feature Files
 Cucumber-JVM with Maven
60% Complete

 Diving Deep into Cucumber


 Using Selenium with Cucumber
 Nightwatch using Cucumber
 Cucumber Summary
 Cucumber Final Assessment

 Bookmarks
 Hands-on  2

Feature File
You have created a feature file

$i
To insert your script

Feature: Play cucumber Champ


As my first cucumber script
I want to show my love for play
Play has become a part of my learning
Scenario: About Play
Given Play a learning platform
When I want to learn
Then I open Play to learn and earn

$ :wq
To comes out of the script.

You are done with creating feature file.


We have set-up our feature file with a script, however, to make it run, you need a runner
file.

In this section, you will learn how to create runner file.

Come to the root folder.

$ cd ~
Go inside bdd folder src/test/java/com/play/bdd.

$ cd src/test/java/com/play/bdd

Create a folder

$ mkdir runner

What is BDD?
 Introducing Cucumber
 Cucumber - Installation
 Gherkin Basics
 Feature Files
 Cucumber-JVM with Maven
60% Complete

 Diving Deep into Cucumber


 Using Selenium with Cucumber
 Nightwatch using Cucumber
 Cucumber Summary
 Cucumber Final Assessment

 Bookmarks
 Hands-on  2

Runner File
Create a Java file inside the runner folder.

$ vi RunPlayTest.java
Once you have created java file, hit i to insert the code.

package com.play.bdd.runner;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
format = { "pretty", "html:target/cucumber" },
features = "classpath:cucumber/play.feature"
)
public class RunPlayTest {
}

Enter :wq to save the folder.

Now, you have runner command.

Enter

$ mvn clear test


It will install all the dependency on Cucumber and Java.

The Script will execute; however, it will list missing steps for execution.

You can implement missing steps with the snippets below:

@Given("^Play a learning platform$")


public void play_a_learning_platform() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}

@When("^I want to learn$")


public void i_want_to_learn() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^I open play to learn and earn$")
public void i_open_play_to_learn_and_earn() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}

There are missing steps which we have to write in the steps.

Come out to bdd folder and create a folder name steps.


$ mkdir steps

Create a java file for our feature file script.

$ vi PlayStep.java
Hit i and copy this steps which you got in previous execution.

Run the Script


After setting up the script. It is time to run the script.

Before running the script add

glue = "com.play.bdd.steps",
in @CucumberOptions the path in public class RunPlayTest.java

Come out to the root folder and move to

$ cd cucumber-jvm-maven
Run the script

$ mvn clean test


This command will run our cucumber test.

Try these step as part of first hands-on.

For your understanding, we have created a folder run and checked the script.

$ git clone https://github.com/dwivedipriyaranjan/cucumberSampleCode.git


git clone https://github.com/dwivedipriyaranjan/calculatorCucumber.git
You can open the folder in Katacoda also.

You all have come to this level that you can create a Cucumber script. But you might find
it hard to write nice and efficient step definitions.

Let's learn how to write and design step definitions.

Use of Anchors

 To begin our step definition use ^.


 To end our step definition use $.

Our script will look like


@Given("^My first cucumber step defination$")

Use of Variable and String


Let's learn how to capture integers in your step definition.

@Given("^I have (\\d+) (.*) in my play$")


public void i_have_in_my_play(int number, String veg) throws Throwable {
System.out.println(format("I have {0} {1} in my play", number, miles));
}

Use of brackets as a capture group so that parameter can be mapped in cucumber.

However, a question would be running in your mind

what does \\d+ and .* stands for?

 d represents a digit.
 + means the use of digit ones or more times.
 \d+ means at least one digit matches.
 . means any character.
 .* it means at least one character matches.

Singular and Plural


If you have a text where you are using the number variable. For example:

There is 1 credit for some course in Play.


There are 2 credits for some course in Play.

Now, you have to design your script so that it handles default use of is and credit for
the singular. For plural, it should use are and credits.

To do so following this:

@Given("^There (?:is|are) (\\d+) (?:credit?|credits) for some course in play$")


public void animals_fed_by_people(int animals, int persons) throws Throwable {
System.out.println(
format("{0} credits(s) ", credits));
}

 (?:is|are) it will check for digit and place is and are accordingly.


 (\d+) will pass our random digit.
 (?:credit?|credits) will check for is and are and place the value accourdingly.

 Random Variable
 For example, I have an application where only value change is happening at one
certain of the point. Or a bot which is replying I love play or I adore play or I
like play.
 How can we randomize that value in our cucumber
 Let's learn how to randomize a variable within the step.
 @Given("^I (?:love|Adore|like) play$")
 public void i_have_a_X_cucumber_step() throws Throwable {
 System.out.println("Step definition with a non-capturing group");
 }

 Here, we have used ?: (question mark followd by colon).


 Output will be
 Given I love play
 Given I Adore play
 Given I like play

 4 of 15

 DataTables Feature File


 Till now we have learned how to get the random value. However, many of you
will be interested in getting data from dataTables.
 Let's learn how to get the data in cucumber.
 Setup Feature file

 Scenario: Data tables


 Given I have the following details for play
 | course | miles | credits |
 | Nightwatch | 200 | 1 |
 | Artillery | 150 | 1.5 |
 | Maven | 100 | 1.5 |
 Here, we use pipe | to create Columns of the table.
 You are done with the data table. Let's use this data table in your script.
Cucumber

 What is BDD?
 Introducing Cucumber
 Cucumber - Installation
 Gherkin Basics
 Feature Files
 Cucumber-JVM with Maven
 Diving Deep into Cucumber
60% Complete

 Using Selenium with Cucumber


 Nightwatch using Cucumber
 Cucumber Summary
 Cucumber Final Assessment

 Bookmarks
 Hands-on  6

DataTable Step
You have seen how to create feature file, let's learn how to call that feature file in your
main script.

@Given ("^I have the following details for play$")


public void i_have_the_following_play_details (DataTable table) throws Throwable
{
for (Map<String, String> map : table.asMaps(String.class, String.class)) {
String course = map.get(“course”);
String mile = map.get(“miles”);
String credit = map.get(“credits”);
System.out.println (format("play details {0} {1}s at the credits of {2}",
miles, course, credits));
}
}

This will create a variable and get the value to our script.
6 of 15


 Home

 My Courses

 Explore

Cucumber

 What is BDD?
 Introducing Cucumber
 Cucumber - Installation
 Gherkin Basics
 Feature Files
 Cucumber-JVM with Maven
 Diving Deep into Cucumber
60% Complete

 Using Selenium with Cucumber


 Nightwatch using Cucumber
 Cucumber Summary
 Cucumber Final Assessment

 Bookmarks
 Hands-on  6

Mapping Table
You feel confused, let's make it more simpler for you.

Create a folder named domain in test dbb. The inside domain creates a java file
names CourseList.java. Copy this code in the java file.

package com.play.bdd.domain;
public class CourseList {

private String course;


private int miles;
private int credits;

public String getCourse () {


return course;
}

public void setCourse (String course) {


this.course = course;
}

public int getMiles () {


return miles;
}

public void setMiles (int miles) {


this.miles = miles;
}

public int getCredits () {


return credits;
}

public void setCredits (int credits) {


this. credits = credits;
}
}

You are using getter and setter concept to set the data value. You need a small change in
the Step file.
7 of 15


 Home

 My Courses

 Explore

Feature file Map DataTable


In the previous card, you have used getter and setter to set the dataTable value.

Now, you need some change in the step.java file.

@Given ("^I have the following details for play$")


public void i_have_the_following_order (DataTable table) throws Throwable {
for (CourseList courseList : list) {
String course = orderItem. getCourse ();
int mile = orderItem.getMiles();
int credit = orderItem.getCredits ();
System.out.println (format("play details {0} {1}s at the credits of {2}",
mile, course, credit));
}
}

Tags
 The different data in the feature files can be organized by using tags.
 Tags must be prefixed by @.
 Features, Scenarios, Scenario Outlines and Examples can be tagged.
 When a feature is tagged, the tag is inherited by all the scenarios in the feature.
Example:

@Login
Feature:Login functionality
@InvalidLogin
Scenario: Login using Blank username and password

This scenario given above will have two tags: @Login & @InvalidLogin.

Usage of tags improves the quality of documentation. It also provides the capability to
filter features/scenarios based on tags.

Hooks
Cucumber supports hooks, which are blocks of code that are executed before and after a
scenario.

 The two hooks supported by Cucumber are @Before and @After.


 @Before is used for the preconditions in a scenario like opening a browser, starting a
server etc and similarly, @After is used for the operations once a test is completed like
closing the browser, clearing browser cache, generate reports etc.
 @After hook will be executed even if the test fails.
 The packages cucumber.api.java.After and cucumber.api.java.Before must be
imported.
 In case of prerequisites specific to a scenario, tagged hooks can be used.
 Order of execution of hooks can be prioritized by using order=n where n can be any
number. @Before hooks will be executed in the increasing order .i.e. 0,1 and so on,
while, @After hooks will be executed in the decreasing order .i.e. 1,0.
 We have completed the learning about Cucumber in the previous topics.
Cucumber can be integrated with tools like Selenium, Watir, and Capybara.
 In real-time applications, Cucumber is often found to be integrated with
Selenium for writing test cases.
 Hence, in this topic, we'll discuss how Cucumber can be used in association with
Selenium.

Cucumber with Selenium - Installation


To integrate Selenium with Cucumber, we have to prepare ourselves right from the
installation. If you remember, we had downloaded few JAR files while setting up
Cucumber. In addition to those, we have to include the following JAR files:

 corbetura
 cucumber-reporting
 mockito-all
 selenium-server-standalone
 cucumber-junit
 junit

These JAR files can be downloaded from the Maven repository, and the selenium-server-
standalone can also be downloaded from the Selenium website.

Features and Step Definitions with Selenium


There is absolutely no difference in writing a selenium Java. You have to follow the same
set as explained before.

But, with Selenium, the step definitions is going to look different. It helps us to widen the
capabilities and will allow us to perform actions which we were not able to do,
otherwise.

Learn the basics of Selenium from the Selenium course available in FrescoPlay.

Here you will learn to set up selenium with Cucumber.

Cucumber with Selenium - Folder structure


As explained before, your folder structure will be the same as you create for the normal
java project.

Changes will come in only your files views.

 You will learn some dependencies to be included in the pom.xml for selenium.
 You will learn how to set up the application set in Feature file.
 You will learn how to include our selenium code in script file.

4 of 9
POM Dependency
Let's begin with the POM file.

You need to set pom dependency copy this dependency and set in pom.xml

<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-core</artifactId>
<version>${cucumber.version}</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.31.0</version>
</dependency>
</dependencies>

Feature file
We need to set this as our resource folder with feature file.

Feature: DuckDuckGo

Scenario: Searching DuckDuckGo

Given I open DuckDuckGo search page


Then the title is "DuckDuckGo Search Engine"
And the DuckDuckGo search form exists

Moving to next, we will see how to write our code in script file.

 Enter :wq to save the folder.


 Now, you have runner command.
 Enter
 $ mvn clear test
 It will install all the dependency on Cucumber and Java.

Nightwatch
You learned, how to configure Cucumber for Java. Let's take a tour on how to configure
Nightwatch with selenium.

Confused with Nightwatch?


Don't worry; you can learn Nightwatch from play DevOps course.

 It is a framework that works with Selenium to perform end-to-end automation.


 It is written in JavaScript.
 Dependency injection is easier as compared with POM.
 Easy to learn.

1 of 8

Getting Started
You will learn the basics of how to create a folder and file need for Nightwatch.

To create cucumber project, follow this steps:

create a folder

$ mkdir sample
$ cd sample
Now create a package.json and nightwatch.conf.js files.

$ vi package.json
$ vi nightwatch.conf.js
It's time to create two folder

 step_definitions

$ mkdir step_definitions

 features

$ mkdir features
It's time to put configuration values in package.json and nightwatch.conf.js.

Package.json File View


Let's set up our package.json first,

Starts with creating a file with name package.json.

$ vi package.json
Copy the value for here and paste this value.
{
"name": "simple-example",
"version": "1.0.0",
"description": "",
"main": "nightwatch.conf.js",
"scripts": {
"e2e-test": "nightwatch"
},
"dependencies": {
"cucumber": "^4.0.0",
"cucumber-pretty": "^1.4.0",
"nightwatch": "^0.9.20",
"nightwatch-cucumber": "^9.1.2",
"phantomjs-prebuilt": "^2.1.15",
"selenium-server": "^3.10.0"
}
}

In this package.json, we have defined our dependencies that we need to install for
running Cucumber.

Nightwatch Config File


After the package dependency setup, to make our application understand where
installed, values are stored so that it can be used. To achieve this we will
create nightwatch.conf.js .

$ nightwatch.conf.js
Copy the following conf details.

const seleniumServer = require('selenium-server');


const phantomjs = require('phantomjs-prebuilt');

require('nightwatch-cucumber')({
cucumberArgs: ['--require', 'step_definitions','--format', 'node_modules/cucumber-
pretty', '--format', 'json:reports/cucumber.json', 'features']
});

module.exports = {
output_folder: 'reports',
custom_assertions_path: '',
live_output: false,
disable_colors: false,
selenium: {
start_process: true,
server_path: seleniumServer.path,
log_path: '',
host: '127.0.0.1',
port: 4444
},
test_settings: {
default: {
launch_url: 'http://localhost:8087',
selenium_port: 4444,
selenium_host: '127.0.0.1',
desiredCapabilities: {
browserName: 'phantomjs',
javascriptEnabled: true,
acceptSslCerts: true,
'phantomjs.binary.path': phantomjs.path
}
}
}
};

step_definitions folder
We have created the folder named step_definitions. Go inside the folder.

$ cd step_definitions
Create a file inside step_definitions folder.

$ vi steps.js
And copy this script.

const { client } = require('nightwatch-cucumber');


const { Given, Then, When } = require('cucumber');

Given(/^I open DuckDuckGo search page$/, () => {


return client
.url('https://duckduckgo.com/');
});

Then(/^the title is "(.*?)"$/, (text) => {


return client.assert.title(text);
});

Then(/^the DuckDuckGo search form exists$/, () => {


return client.assert.visible('input[name="q"]');
});

Cucumber

 What is BDD?
 Introducing Cucumber
 Cucumber - Installation
 Gherkin Basics
 Feature Files
 Cucumber-JVM with Maven
 Diving Deep into Cucumber
 Using Selenium with Cucumber
 Nightwatch using Cucumber
60% Complete

 Cucumber Summary
 Cucumber Final Assessment

 Bookmarks
 Hands-on  6
step_definitions folder
We have created the folder named step_definitions. Go inside the folder.

$ cd step_definitions
Create a file inside step_definitions folder.

$ vi steps.js
And copy this script.

const { client } = require('nightwatch-cucumber');


const { Given, Then, When } = require('cucumber');

Given(/^I open DuckDuckGo search page$/, () => {


return client
.url('https://duckduckgo.com/');
});

Then(/^the title is "(.*?)"$/, (text) => {


return client.assert.title(text);
});

Then(/^the DuckDuckGo search form exists$/, () => {


return client.assert.visible('input[name="q"]');
});

5 of 8


 Home

 My Courses

 Explore
 We have defined our steps folder, now let's define our features file.
 $ cd ..
 This command will be used to come out from step_definitions folder.
 $ cd features
 $ vi duckDuckGo.feature
 This will create feature file and copy the value
 Feature: DuckDuckGo


 Scenario: Searching DuckDuckGo


 Given I open DuckDuckGo search page

 Then the title is "DuckDuckGo Search Engine"

 And the DuckDuckGo search form exists


 Scenario: Searching DuckDuckGo again


 Given I open DuckDuckGo search page

 Then the title is "DuckDuckGo Search Engine"

 And the DuckDuckGo search form exists

Run Script
Come out of the features folder

$ cd ..
Run the command to install all the dependency from package.json.

$ npm install
It will install all the dependency.

$ npm run e2e-test


This command is used for running the cucumber script.
For more detailed information on cucumber, visit our cucumber course.

Nightwatch Folder structure


You can clone github project to see a sample NightWatch project.

You might also like