Cucumber Test: Be a Pro in Quick 10 Minutes

This Post Will Cover

Share and Enjoy !

All about Cucumber Test

A short introduction of BDD

BDD (Behavior-driven development) is an evolution in the thinking of test-driven development (TDD) and Acceptance Test-Driven Development(ATDD) Planning.

The test automation team usually takes reference from requirement documents and automates in a similar fashion to how the developer develops the application.

It creates ambiguity between how the test and development team interpreted the requirements. On top of it, automation is done after the development is completed.

In Cucumber-driven testing of the gherkins, the syntax is the acceptance criteria and it becomes the required documentation for both the development and testing team.

A Unit test checks if developers are building the thing right and an acceptance test is to check if the developers are building the right things.

BDD aims to help focus development on the delivery of prioritized, verifiable, business value by providing a common vocabulary (ubiquitous language) that spans the divide between Business and Technology.

A language structured around the domain model and used by all team members to connect all activities of the team with the software.

Establishing the goals of different stakeholders requires a vision to be implemented. Drawing out features that will achieve those goals using feature injection.

Involving stakeholders in the implementation process (Acceptance criteria, features, etc) using examples to describe the behaviors of the application, or units of code. Automating those examples to provide quick feedback and regression testing.

Setup Cucumber and More Details On Cucumber:

Cucumber is a BDD(Business-driven development) tool that runs acceptance testing. It reads plain text descriptions of the application features with examples and scenarios.

later using cucumber they can be converted to automation. It is an easy interface between developers, testers, and business people.

Many times it is seen, business personnel who does not code or having little knowledge of coding prefers to do manual testing instead of automation testing. That makes acceptance testing slower.

To make it speedy Cucumber gives an easy to write and coding interface. It is an iterative development and testing process where tests are written before the real development of the code of the real application.

So in the initial phase, all tests are supposed to be failed but slowly, when developers start implementing the features, tests start passing.

BDD is an extension of TDD. Cucumber or JBehave acts as a bridge between Business and Technical language.
Here is a nice link on BDD
Here is another one
The overall cucumber takes a big effort to ensure the tests can be read and written by stakeholders themselves.

This feature file written in Gherkin is the signed-off document from the stakeholders to the development and testing team.

Cucumber Test
Cucumber Test

What are the objectives of using cucumber in BDD?

  1. Validate if the right system is being built.
  2. Validate if a business, users, customer point of view are captured.
  3. Validate if the correct elaborative (with example) document is present about what the system should do.
  4. Validate if the teams have a shared understanding of what is being built.
  5. Validate if the definition of done is achieved.

The expected output of using cucumber in BDD?

  1. The confirmation of building the system correctly.
  2. Living documentation(once automated), no need to maintain long time-consuming documentation.
  3. Reduce the volatile ness and cuts down the cross discussion understanding mismatch.

Who is the primary audience?

  • Product Owner(PO)
  • Business Owner(BO)
  • Business Analysts(BA)
  • Subject Matter Experts(SME)
  • Testers
  • Developers
  1. The cucumber framework helps the business stakeholders to write proper acceptance testing test cases.
  2. It reduces communication gaps between domain experts and development as well as testing teams
  3. Under the hood step definition translates business-facing language(Gherkins) to actual language(java)

How BDD viz Cucumber works?

Cucumber translates the business language to pure language.

Cucumber Test
Cucumber Test
  • It is written in plain text.
  • It is understood by the business, developers, and testers.
  • It targets the business requirements.
  • A significant proportion of functional specifications are written as user stories.
  • It provides just enough living document.

Where to Start?

  • BDD cucumber starts with a conversation between stakeholders.
  • It is goal is to determine the features and derive acceptance criteria.
  • It defines the definition of done.

Core principles of Cucumber

  1. Developers write the test before the code.
  2. Developers will not touch or code anything other than covering the failing test cases.
  3. The test case will cover the acceptance criteria for a user story.
  4. There should be a joint effort to write the test cases. Developers, testers, and customers should join in the writing process of the test case development
  5. These test cases are behavioral or high-level tests but not unit tests.

Cucumber is governed by the cucumber-Gherkin language.

Advantages of using Cucumber in BDD :

  • Unit tests are code-driven and actually produce code. Driven by Business value.
  • Business drives the development via a testing process that focuses on behavior rather than developed code.
  • Refactoring improves the code and stability of the application
  • Test first approach reduces the cost of bugs
  • Simple Given, When and Then approach, so all stakeholders can design the feature of the application. It provides an easy collaboration between stakeholders, business analysts,QA team,s, and developers.
  • Freestyle English writing focuses on user experience. Easy to understand.
  • Quick, Easy to set up, and executable.
  • An efficient tool for testing.
  • Users can provide examples to clarify requirements.
  • Ensures automated code coverage.
  • Provides valuable tests.
  • It relies on shared understanding by discussing examples. Hence all team members know what they are actually trying to achieve.


  • Tests become part of the maintenance overhead
  • Tests need to be rewritten when requirements change
  • It targets the unit level coding rather than what the code should actually do
  • Sometimes developer team finds it a waste of time if it is too poor.

Cucumber is a tool that can execute a plain text functional description as an automation test. So cucumber is an acceptance testing tool but not an automation tool and Gherkin is an acceptance testing language.

Cucumber acting as a bridge collaborates between stakeholders of the projects. Cucumber originally built in Ruby but currently supports java.

Setup :

Cucumber needs the following jars:

See also  Constant Concept Simplified in Java
Cucumber Test
Cucumber Test

Open Eclipse, Create a java project, right-click on the project, go to build path then configure build path and click on library lab and click on Add External jar, select cucumber jars to add. Click on Open to add them to the project.

Add all selenium related jars in the same way to the project.

Now for setting up the project, we need to create two packages

  • source
  • test

The source contains all of the source code coming from developers and test is going to hold all test classes and methods.

Cucumber folder structure


Cucumber provides a shared understanding of acceptance criteria. It documents the system details. In cucumber, the regression test is a violated assumption.

Few terms to relate Cucumber

  • User Story: Agile term used to describe an end to end journey of a feature.
  • Cucumber: It is used to describe the interpreter used to process Gherkin syntax.
  • Tear Down: This term used in automation to describe the series of actions executed at the end of scenario execution.
  • Setup: Setup is used in automation to describe the series of actions executed at the beginning of scenario execution.

How to Write a Good Step in Gherkin?


Lines are called steps. Good steps are easy to understand and as obvious as they can be-the text is written in a business readable domain language known as Gherkins.

Gherkin will go through each step written in the step definition file. The step given in the feature file must match with the step definition file.

Step definition

To execute steps we need automation code. Steps are matched via Regular expression. Step definition should be written in a pure coding language like -Java. It is written by the developers for each step.

When Cucumber executes a Gherkin step in the scenario, that links to the step definition for actual code.

Scenario: Visitor count
Given   :I have 15 visitors at the store

The equivalent step definition is as follows

package myTest;
public class MyStepDefinition{
    @Given("I have (int) visitors at the store")
    public void i_have_n_visiors_at_the_store(int visitors){

You can use Java’s advanced concept of Lambda expression too

package myTest;
import cucumber.api.java8.En;
public class MyStepDefinition implements En{
@Given("I have (int) visitors at the store",(Integer visitors)->{

Step definition expression

A step definition expression can be of the following types

  • Regular expression
  • Cucumber expression.

State Management

A step definition may convert or change the present state of the application to a subsequent step definition. It can be done by putting the state in an instance variable.

You need to create the test cases in such a way that the state from one scenario should not propagate to another scenario. Leaking states will not allow the test cases to run in isolation. Debugging will become tough.

However, It is possible to share the state between steps in a scenario. In that case, store your object state in a variable in your step definition. However, it will make the steps tightly coupled.

How to stop state leaking from Scenario to Scenario?

In order to avoid the state licking, you need to abide by the followings:

  • Clean your database in a Before hook. Most of the testers miss this.
  • Do not strictly use global or static variables. They the second most culprit for state leaking.
  • Delete cookies when a browser or session is shared between the scenarios.


If step definition is not attached to a feature file or a scenario,the file,class,library,package name of the step definition does not cause any harm to Gherkins steps that will match. It always depend the step definition expression.

Auto Code Snippet Generation

In case when Cucumber receives a Gherkin step without a matching step definition, it will automatically print a function/method snippet matching with the Cucumber expression. You can always execute the Gherkin script before writing any concrete script. The auto-generated code snippet will guide you further. In that case, you have to implement the method pointed out by Gherkin.

Note: In order to get the suggestion and summary printed, you need to summary plugin attached to your editor.

Let’s say we have one Gherkin step defined as:

Given : The book has 10 pages

Now if the matching step definition is not found, Cucumber will automatically generate:

@Given("The book has 10 pages")
public void The_book_has_pages(int int1)
//this place is for your implementation

Step Arguments

From the step definition, Cucumber can automatically extract text and convert it to an equivalent data type(like int) and passes as an argument to the method.

The number of parameters in the method should exactly match what is defined in the step definition. Otherwise, the cucumber will throw an error and will generate the equivalent code snippet.

Transformation of Steps during Implementation

A step is similar to the method call or a function call from an implementation perspective. The steps will be defined in the *.feature file.

During transformation the below steps happen:

  • The cucumber will try to match a step against the step defined in the step definition using a regular expression.
  • Cucumber accumulates all groups and variables.
  • Cucumber flats all the data provided in the step definition.
  • The cucumber will pass all these artifacts to the method.
  • The cucumber will start executing the test.

Note: Once Cucumber registers the methods, the keywords(Given, When, Then, And, But) do not have any significance.

Results if step execution:

Each step will have one of the following results:

  • Success– The corresponding step definition is found and the execution happens. It is marked as Green. The result does not depend on the outcome of the step executing.
  • Failed- The corresponding method is found but during execution, the step caused an error. The result does not depend on the outcome of the step executing. These steps are marked as Red.
  • Undefined- The corresponding step is not found and the step becomes undefined. All the remaining steps are skipped during execution. They are marked as yellow. If you use — strict command to execute, the cucumber will exit with exit code 1.
  • Pending-  Similar to Undefined but the step function actually invokes a pending method. A pending method is an unfinished method. They are marked as yellow. If you use — strict command to execute, the cucumber will exit with exit code 1.
  • Skipped-  Steps like Undefined, Pending, or skipped due to failed steps are actually never get executed. They are marked as cyan.
  • Ambiguous- In case you do not have a unique step definition, cucumber will raise AmbigousStepDefinitionsException. You have no other choice to fix it.

What is Gherkin in Cucumber and How to Use it?

Gherkin is a language in which cucumber takes business specifications. Gherkin is the business confronting, domain-specific language. It helps to express the business requirements without going into details about the implementation.

It is some portion of a cucumber test suite, mostly put away in a feature file. It connects the human concepts of cause-effect to the software concept of input and output. It must be composed by the Gherkin syntax, rules with the goal that Gherkin can peruse them.

Gherkin is a ubiquitous language for BDD which cucumber understands. It helps us to describe the software behavior without detailing how that behavior is implemented.

Gherkin links the acceptance test to the automated test. It means that if we change an acceptance test, the underlying test should fail. It signifies that we can be confident that the system matches the specification.

As part of BDD, we want to write many automated tests to improve our confidence in the product. We want these tests to be understandable and valuable.

Gherkin also creates the documentation and skeleton of the tests that you are going to automate.

cucumber working model
cucumber working model

The Gherkin is very famous as:

  • It enables us to express our requirements in plain English language.
  • It forces us to express each scenario clearly in terms of interactions with the system.
  • It allows us to document acceptance tests in a language that dev, QA, and the business can understand.
  • It allows the three amigos to collaborate and test in a common language.

Gherkin is :

  • Business readable domain-specific language.
  • Represents tests in natural languages.
  • There is a total of 35+ languages supported. Localized.
  • It is a line-oriented language just like YAML and python.
  • It is also keyword-oriented like feature, Scenario, given, when, then, but, and
  • It represents the user’s scenario hence become the documentation of the same.
  • It provides the Automated test cases skeleton.

What is not Gherkin?

  • It is not a programming language.
  • It is not a unit testing tool.
See also  Class UnsatisfiedLinkError in Java

How to write a good Gherkin syntax

  • starts with a when(Gherkin keyword).
  • There is one when per scenario- it represents the single responsibility principle.
  • One action per step. (Each line is called a step)
  • Follow Brian Marick’s Agile testing quadrants/Mike Cohn’s test automation pyramids.
  • Do not mix domains.
  • The maintainability of the scripts is given the highest priority.
  • Check if the steps are usable. Our objective is to make the steps reusable as far as possible.
  • There should be minimum numbers of ‘try’.
  • Start with a conversation.
  • Use tab or spaces for increasing readability via proper indentation.

Remember Gherkin scripts make great Acceptance criteria but not a good user story.

A simple example of Gherkin

Feature:  adding
Scenario: add two numbers
Given:    the two inputs like 2 and 2
When:     the calculator runs
And:      operates sum operation
Then:     the output of the summation of the two given numbers like 4

Why Gherkin script?

  • It helps to isolate the functionality.
  • It helps to isolate the issue.

The Exceptions of Gherkin rules

  • Gherkins rule does not apply well when we are making End to End tests.
  • Gherkins rule does not apply well when we are working on regression tests.

How to make Gherkin Maintainable and reusable?

We need to make sure that each step does only one action. This makes the code more maintainable and reusable.

Best Practices while implementing Gherkin in your project

While implementing Gherkin in your project you need to take care of the following best practices:

  • It is always advisable to combine common scenarios. It will give reusability and modularity.
  • Your scripts should be as modular as possible.
  • Your steps should be as clear as possible.
  • You need to create your own traceability about which script is covering what requirements.
  • The traceability will also give you a complete connection about the Scenario and requirements.
  • Create your script in such a way that each scenario gets executed separately.
  • Create your script in such a way that every feature file gets executed along with the scenario.
  • Create your script in such a way that steps are independent of each other.

Typical Gherkin syntax

Feature:[About the scenario- Title]
Given  :[starting context/precondition/known state]
When   :[Key action/Event/Trigger]
Then   :[Outcome/actual result]

The transformation from Business to Gherkins

let’s assume the below problem statement

When I enter username as testuser and password as test123 and click on the login button, I must see the welcome screen.

Corresponding Gherkin-BDD

Given    : I am on the login page
When     : I enter username as testuser
And      : I enter password as test123
And      : I click on login button
Then     : I must see the welcome page.

How to save Gherkin?

Gherkins document is saved as. feature extension. It is a text file. Later this becomes the testcase and test file.

Components of Cucumber Gerkin

  • Features
  • scenarios
  • Gherkin -Given When Then And But
  • Steps
  • Tags
  • Comments
  • Data table
  • Scenario outline
  • Background
  • pyString

The actual text acts as the high-level information. It gets started with the keyword called- Feature followed by a colon. Then followed feature name and optional description.

Feature: Generate a customer Loan

A good Feature can be of two types

  • Value Centric
  • Role Centric
Example of Value Centric
<In Order to> create a customer Loan 
<As a> valid user
<I want> an ability may be a drop down that can list all possible abilities like create loan etc
Example of Role Centric
<As a> valid user
<I want> an ability may be a drop down that can list all possible abilities like create loan etc
<so that> I can create a Loan for my customer

Note: There are no guidelines for Gherkin’s naming convention. You can decide during your project meet to decide what works best for your project.

Best practices to write a feature file

  • The extension of the feature file is .feature
  • One feature file ideally should talk about only one feature.
  • The feature should start with a keyword named- Feature then the feature name
  • One feature file may contain multiple scenarios.

A Scenario is a concrete example of system behavior that can describe a particular business situation. Scenarios can be independent and isolated.

They can exhibit a happy path (positive testing) and a rainy path(negative testing). It starts with the Scenario keyword followed by a suitable title.

We must keep the scenario short and to the point. the scenario starts with the keyword Scenario followed by the scenario name.

A scenario consists of the following components:

  • Given- setup initial state
  • When-perform some action
  • Then- Check end state
  • And But- for additional operations

To put a system in a known state before the user (or an external system) starts interacting with the system(in the When steps). G

Evans is the preconditioning step in use cases. We must avoid talking about user interaction in Given. It is a test step that defines the context. In technical terms, it is the prerequisite for the steps.

Does with Given

  • Given may interact with the system.
  • Given should be expressed as a preexisting condition or any business requisite.
  • Given is something that indicates that we accept to be true in a scenario.
  • Given can accommodate test data.
  • We should rarely have an error in the Given statement.

Don’ts with Given

  • Given should not perform interactions relevant to scenarios.
  • Given should not be expressed like an action.
  • No functionality should be changing in the Given statement.

To resolve the key action that users perform. So it is the action part. When describes things that the user(or some other actor) does to the system.

Does with When

  • When should describe what the user does?
  • when represents what developers are going to develop and what the test case are testing.
  • It represents what everyone is being paid to build and test.

Don’ts with When

  • When should not describe things that the system does?

Then is to observe the outcomes. Then describes what the system is expected to do(in response to something done in the when clause).

The observation should be related to business values/benefits in our feature description. The observation should inspect the output of the system(a report/User interface/command output) and something which has no business value and instead part of the implementation. So it is the result part.

Does with Then

  • Then should describe what the system should do.

Don’ts with When

  • When should not describe things that the user does?
And But:

If we have several Given When or Then steps then And or But can be used to read scenarios more clearly.

Example of good Scenario

Scenario: Generate a customer loan
Given:    User on the loan home page
When:     User clicks on create loan
And:      Provide Loan details
Then:     The loan should get created 
And:      Submitted for approval


Keywords in cucumber can be placed with comments. Comments start with a # symbol. Comments allow users to provide details about the ‘Feature’ or ‘Scenario’.

Multiline Arguments:

Multiline arguments are useful when using with Data table.

@Scenario: User login to Loan Application
given: user has number of roles given below:

Multiline String or pyString

Multiline String(also known as PyString) are handy for specifying a larger piece of text. The test should be offset by delimiters consisting of three double quote(“””) marks on lines themselves.


Background executes before each scenario. It provides a context (state setup) to the scenario in the feature. Do not use the background to setup a complicated state unless that state is something the reader actually needs to know.

The background should be short as after all you are expecting the user to actually remember this stuff reading your scenario. Background may content some steps of scenario.

Example of background

Background: User logging into Loan application
And:        User is a valid user
given: user has number of roles given below:
then:      the user is valid application user.

Use of Datatable in Cucumber:

Cucumber allows us to put the table directly in the Gherkin script. We need to use pipe symbol to separate columns in the table. We can use ctrl+alt+l(lowercase of L) to align the tables in cucumber.

Feature: adding
Scenario: add two numbers
Given: the two inputs <<input1>>,<<input2>> like 2 and 2
When: the calculator runs
And: operates sum operation
Then: the output is the summation of the two given numbers <<>result> like 4
|   1  |   1  |  2   |
|   2  |   3  |  5   |

An alternative way to pass data table:

We can pass List<String> to a step definition to use as data table

Given :the following books
| Pride and Prejudice |
| The Great Gatsby    |
| Lord of the Rings   |

You need to define it as a List<String>. Cucumber will automatically make the List<String> flat by using it’s inbuilt method DataTable.asList(String.class) before executing the step definition.

@Given("the following books")
public void the_following_books(List<String> books){}

Advantages of Gherkin

  • Easy consumable for non-programmers (business stakeholders) and developers.
  • Testers can treat this as a base for their testing task and kick start the coding.
  • It converts the user stories into simple and easy to understand.
  • It can easily target the business requirements.
  • The user story covers almost all functional specifications.
  • It becomes documentation too.
  • It connects the automated test cases to acceptance test cases.
  • Gherkin produces easily reusable codes.
See also  Class PipedInputStream in Java

Disadvantages of Gherkin

  • If the requirement is not captured as per proper Gherkin and cucumber syntax, the maintenance of the test case is going to be high, resulting in low ROI.
  •  The out of the box gherkin may not work for all real application development scenario.
  • Gherkin does not work well when you work on the legacy codebase.
  • Gherkin really needs high collaboration, communication, and business engagement.
  • It May is not suitable for large projects.

How to Use Tags in Cucumber Gherkin?

Every scenario and features should be marked with arbitrary tags. it helps to map to unit test framework “categories”. Scenarios inherit feature tags. A feature can have multiple tags. Tags are using with @ symbol. Remember @ignore is a special tag. Tags are a great way to organize our test cases, features, and Scenarios.

If you want to specify that before and after hooks to be executed with a specified tag only, tags allow you to create that custom running options like


You can also specify the logical AND and OR logic

@Before(@dev,[email protected])

The objective of using tags:

Tags enable you to perform the below activities:

  • Allow you to create a subset of the actual test case asset and execute them
  • Creates a provision to scope a hook to a subset of Scenario.

An example of a tag

Uses of tags
  • Group features into feature supersets(like smoke, regression, important)
  • Differentiate between @slow and @fast executing tests.
  • @wip shows the test case is being built and should not get incorporated in the test suite
  • @weekly are such combination of test cases which run weekly once.
  • @daily is such a combination of test cases that run daily
  • Similarly, we can have @hourly and @humanexecuted.
Background       :I am logged in
Scenario outline :Check contact information
Given            :I am on the Account information page
When             :I click on the Edit profile link
Then             :I should see the "contact information"

A feature or scenario may have n numbers of tags depends on your requirements.

@dev @qa @stagiing @hourly @weekly ....[so on]
Scenario : Test login functionality of an application
Feature :  Test login functionality of an application

Where you can use tags?

Tags can be used with these Gherkin elements

  • Feature
  • Scenario
  • Scenario outline
  • Example

Where you can use tags?

you can not use tags for the following scenarios

  • Above Background
  • with Steps like Given, When, Then, And, But

Inheritance property of Tag

Tags in cucumber follow a hierarchical model. The child tag always inherits the tags of the parent tag.

like the tags placed above the Feature will be automatically applied to downstream elements like Scenario, Scenario Outline, Example. similarly, Tags placed along with the Scenario outline will be inherited by Examples.

How to execute test cases with the help of tags in cucumber?

We can very well instruct JVM to execute the particular tag or tags by providing the tag/tags name in the command line.

Option-1 Direct injection
mvn test -Dcucumber.options='--tags @dev and @fast
Option-2 By setting an environment variable
set CUCUMBER_OPTIONS='--tags "@dev and @fast"
mvn test
Option-3 By changing JUnit runner class
@CucumberOptions(tags="@dev and @fast")
public class RunCucumberTest{}

How to ignore test cases with the help of tags in cucumber during execution?

We can very well instruct cucumber to ignore the particular tag or tags by providing the tag/tags name in the following manner.

Model-1 Using Junit runner class
@CucumberOptions(tags="not @dev") 
public class RunCucumberTest{}
Model-2 Filtering the line
  • Use file.feature:line pattern
  • use –scenario option

Tag Expression-Infix boolean expression

A tag is an infix boolean expression.

Sl noExpressionMeaning
1@fastScenarios tagged with @fast tag
2@gui or @databaseScenarios tagged with @gui tag or @database tag
3@smoke and @ fastScenarios tagged with @smoke tag and @fast tag
4@wip and not @slowScenarios tagged with @wip tag and not tagged with  @slow tag

Similarly, you can create your own custom infix expressions.

How to use tags for documentation?

Tags can connect to external systems like Jira ticket or ALM requirement number or any other systems

@RQ-small32.45 @Defect-234
Feature: interest calculation for home loan

You can use one of the custom plugins available to create an HTML link for pointing to an external tool.

How to use Custom Tags in cucumber?

Developers and QA or any other team use some of the customs created tags to identify, segregate and take appropriate actions on a script.


What are Hooks in Cucumber Gherkin?

Hooks are basically a block of code that helps in the cucumber execution cycle. Hooks are mostly used in the setup and teardown of the environment before and after a scenario execution.

Hooks addition and execution does not affect the actual scenario execution. Hooks can be declared in any class. Hooks are defined inside of a step definition file.

Hooks can be of the following type:

  • Scenario hook
  • Step hook
  • Tagged hook
  • Global hook
  • Single runnable hook
  • After configuration hook
  • Around hook

Scenario hook

Scenario hook runs for every scenario where it is defined.

Scenario hook can be of two types:

  • Before hook
  • After hook
Before hook

A Before hook runs before the scenario. So the hook gets executed just before the first line of the Scenario.

Syntax of Before hook
public void setUpEnvironment(){}
//lamda style

Before hook is not visible to people who go through only the feature file. Alternatively, you can use background more than Before. As it gave more clarity to the nontechnical people.

You can certainly use Before hooking for low-level code generation like opening a browser or cleaning up a database or clearing a cookie etc.

Order in hook

You can insert an order keyword to provide a hook an ordering like

public void openBrowser(){}
public void clearDataBase(){}
//using lamda
After hook

An After hook runs after the scenario. So the hook gets executed just after the last line of the Scenario. The Steps can be failed, undefined, pending, skipped.

Syntax of After hook
public void tearDownEnvironment(Scenario scenario){}
//lamda style
After((Scenario scenario)->{});

The Scenario parameter is optional though.

Step hook

Step hook gets executed before and after a step. These hooks have a invoke around semantics. Like if BeforeStep hooks get executed, the AfterStep hook will also get executed. In case if the step does not pass, its hooks will be ignored.

Syntax of BeforeStep
public void setUpBrowser(Scenario scenario){}
//lamda style
BeforeStep((Scenario scenario)->{});
Syntax of AfterStep
public void tearDownBrowser(Scenario scenario){}
//lamda style
AfterStep((Scenario scenario)->{});

Tagged hook

Based on the tags used, you can use hooks using conditions. It is a custom execution for a particular hook based on the tag used.

Syntax of Tagged hook
public void closeMobileApp(Scenario scenario){}
//lamda style
After("@mobileApp",(Scenario scenario))->{});

Global hook

Cucumber-JVM is not having any Global hook.

Single runnable hook

Cucumber-JVM is not having any Single runnable hook.

After configuration hook

Cucumber-JVM is not having any After configuration hook.

Around hook

Cucumber-JVM is not having any Around hook.

A common use of hooks in code

Most commonly you will be using the Before and After hook in your test. We create a real-time scenario to understand hooks better.

  • Create a Maven project in Eclipse.
  • Create and configure the pom.xml to add a necessary dependency.
  • Create a package named testMyHook at src\test\java
  • Create a step definition file called
package testMyHook;
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 testMyHook{
WebDriver driver=null;
public void setUpEnvironment()
driver=new FirefoxDriver();
@Given("^user navigates to$")
public void user_navigates_to_google(){
@When("^user search test on google$")
public void user_search_test_on_google(String searchString){
@Then("^user should see the test result$")
public void user_should_see_the_test_result()
//check something
public void cleanUp()
  • Create a feature file named as “testMyHook.feature” under the same package.
  • Scenario outline- Testing my hooks
  • Feature-  Scenario outline
  • Create a runner class- in the package
package testMyHook;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;


public class runMyTest{}
  • Save the file
  • Right-click on the file and run as Junit.
The output will be
@Before hook
@After hook

In case you want to run the file as TestNG, download and attach cucumber-Testing addins and run as TestNG.

Advantages of Hooks

  • Provides better code management.
  • Reduce code redundancy.
  • Increase reusability.
  • Provides code optimization.

Share and Enjoy !

8 thoughts on “Cucumber Test: Be a Pro in Quick 10 Minutes

  1. I reached out previously and hadn’t heard back from you yet. This tells me a few things:

    1) You’re being chased by a T-rex and haven’t had time to respond.
    2) You aren’t interested.
    3) You’re interested but haven’t had a time to respond.

    Whichever one it is, please let me know as I am getting worried! Please respond 1,2, or 3. I do not want to be a bother.

    ================================Original Message=============================

    Hi ,

    Sorry to intrude your mailbox.

    I saw you linked to from

    I would like to bring to your attention a resource I recently created – Guru99. The content is up to date and very in-depth.

    I did be obliged if you link to it.

    As a thankyou, I would be glad to share your page with our 27k Facebook/Twitter/Linkedin Followers.


  2. I reached out previously and hadn’t heard back from you yet. This tells me a few things:

    1) You’re being chased by a T-rex and haven’t had time to respond.
    2) You aren’t interested.
    3) You’re interested but haven’t had a time to respond.

    Whichever one it is, please let me know as I am getting worried! Please respond 1,2, or 3. I do not want to be a bother.

    ================================Original Message=============================


    I stumbled upon your site today while searching for data on KEYWORD. You have awesome posts. Great Work!

    I couldn’t help notice that your linked to at your page

    I wouLd like to suggest an article I recently created which is more in-depth and well researched article .

    I would be honoured if you link to it.

    I did be happy to share your page with our 40k Facebook/Twitter/Linkedin Followers.


  3. I’ve learn several good stuff here. Certainly value bookmarking for revisiting. I wonder how so much effort you place to create such a wonderful informative website.

  4. Hi! This is kind of off topic but I need some guidance from
    an established blog. Is it difficult to set up your own blog?
    I’m not very techincal but I can figure things out pretty quick.
    I’m thinking about setting up my own but I’m not
    sure where to begin. Do you have any points or suggestions?


  5. If you are going for best contents like I do, only visit
    this web site daily as it presents quality contents, thanks

  6. Pretty component of content. I just stumbled upon your blog
    and in accession capital to claim that I acquire in fact enjoyed account
    your weblog posts. Any way I will be subscribing to your augment and even I achievement you get
    entry to constantly fast.

Leave a Reply

Your email address will not be published. Required fields are marked *