What is Cucumber and How to Work With Cucumber?

digitization, transformation, binary

Table of Contents

Share and Enjoy !

Setup Cucumber and More Details On Cucumber

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. Test automation team usually take reference from requirement documents and automate in similar fashion to how the developer develop the application. It creates ambiguity between how test and development team interprete the requirements. On top of it automation is done after the development is completed.

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

Ads code goes here

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 real development of 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- https://www.atlassian.com/blog/software-teams/making-the-shift-to-behavior-driven-development
Here is another one-
https://www.guru99.com/download-installation-junit.html

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 form the stakeholders to the development and testing team.

Cucumber workflow
Cucumber workflow

What is objectives of using cucumber in BDD?

  1. Validate if the right system is being built.
  2. Validate if business,users,customer point of view are captured.
  3. Validate if the correct elaborative (with example) document is present about what system should do.
  4. Validate if the teams have the 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 are the primary Audience?

  • Product Owner(PO)
  • Business Owner(BO)
  • Business Analysts(BA)
  • Subject Matter Experts(SME)
  • Testers
  • Developers
  1. Cucumber framework helps the business stakeholders to write proper acceptance testing testcases.
  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 work principle
Cucumber work principle
  • It is written in plain text.
  • It is understood by the business,developers and testers.
  • It targets the business requirements.
  • 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 testcases.
  3. The testcase will cover the acceptance criteria for an user story.
  4. There should be a joint effort to write the testcases. Developers, testers and customers should join in the writing process of the testcase development
  5. These testcases are behavioral or high level tests but not unit tests.

Cucumber is governed by cucumber-Gherkin language.

Advantages of using Cucumber in BDD :

  • Unit tests are code driven and actually produces code. Driven by Business value.
  • Business drives the development via 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 analyst,QA team and developers.
  • Free style English writing focuses on user experience. Easy to understand.
  • Quick,Easy to setup and executable.
  • Efficient tool for testing.
  • User can provide example 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.

Disadvantages:

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

Cucumber is a tool that can execute a plain text functional description as 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:

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 the 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

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
       ./config
       ./features
           /step_definition
              mystep.rb
           /support

Cucumber provides shared understanding of acceptance criterias. 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?

Steps

Lines are called steps. Good steps are easy to understand and as obvious as it 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 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;
import cucumber.api.java.en.Given;
public class MyStepDefinition{
    @Given("I have (int) visitors at the store")
    public void i_have_n_visiors_at_the_store(int visitors){
    System.out.println("Visitors"+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)->{
System.out.println("Visitors"+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 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 other 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.

Scope

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 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 that is defined in the step definition. Otherwise 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 implementation perspective. The steps will be defined in the *.feature file.

During transformation the below steps happen:

  • Cucumber will try to match a step against the step defined in the step definition using regular expression.
  • Cucumber accumulates all groups and variables.
  • Cucumber flats all the data provided in the step definition.
  • Cucumber will pass all these artifacts to the method.
  • 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, cucumber will exit with exit code 1.
  • Pending-  Similar like 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, 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 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 details about the implementation.

It is  some portion of a cucumber test suite,mostly put away in 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 an 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 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 with 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 which 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 are total 35+ languages supported.Localized.
  • It is line oriented language just like YAML and python.
  • It is also keyword oriented like feature,Scenario,given,when,then,but,and
  • It represents the users scenario hence become the documentation of the same.
  • It provides the Automated testcase’s skeleton.

What is not Gherkin?

  • It is not a programming language.
  • It is not a unit testing tool.

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.
  • Maintainability of the scripts are given highest priority.
  • Check if te 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 good when we are making End to End tests.
  • Gherkins rule does not apply good 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 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]

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
Feature

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 is no guidelines for Gherkin’s naming convention. You can decide during your project meet to decide what work best for your project.

Best practices to write feature file

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

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 happy path (positive testing) and rainy path(negative testing). It starts with Scenario keyword followed by a suitable title. We must keep the scenario short and to the point. scenario starts with the key word 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 and But- for additional operations
Given:

To put a system in a known state before the user (or an external system) starts interacting with the system(in the when steps). Givens are the precondition steps in use cases. We must avoid talking about user interaction in Given. It is a test step that defines the context. In technical term it is the prerequisite for the steps.

Does with Given

  • Given may interact with the system.
  • Given should be expressed as 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.
When:

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 testcase 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:

Then is to observe the outcomes. Then describes that 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 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 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

 

Comments

Keywords in cucumber can be placed with comments. Comments starts with a # symbol. Comments allows user 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:
|userRole|
|user_Normal|
|Loan_Admin|
|Process_Expert|

Multiline String or pyString

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

Background

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

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:
           |userRole|
           |user_Normal|
           |Loan_Admin|
           |Process_Expert|
then:      the user is valid application user.

Use of Datatable in Cucumber:

Cucumber allows us to put 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
|input1|input2|result|
|   1  |   1  |  2   |
|   2  |   3  |  5   |

Alternative way to pass datatable:

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

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 as simple and easy to understand.
  • It can easily target the business requirements.
  • The user story covers almost all functional specifications.
  • It becomes a documentation too.
  • It connects the automated test cases to acceptance test cases.
  • Gherkin produces easy reusable codes.

Disadvantages of Gherkin

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

How to Use Tags in Cucumber Gherkin?

Every scenarios 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 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

@Before('@mobileApp')

You can also specify the logical AND and OR logic

@Before(@dev,@wip)
@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 testcase asset and execute them
  • Creates a provision to scope a hook to a subset of Scenario.

An example of tag

@SmokeTest
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 are such combination of test cases which run daily
  • Similarly we can have @hourly and @humanexecuted.
Background       :I am logged in
@wip
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
or 
Feature :  Test login functionality of an application

Where you can use tags?

Tags can be used with these Gharkin 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 applicable to downstream elements like Scenario,Scenario outline,Example. similarly Tags placed along with 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 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 a 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 system 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 plugin available to create a HTMl link for pointing an external tool.

How to use Custom tags in cucumber?

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

@dev_delivered 
@QA_ready
@acceptance_waiting

What are Hooks in Cucumber Gherkin?

Hooks are basically a block of code that helps in cucumber execution cycle. Hooks are mostly used in 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 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
@Before
public void setUpEnvironment(){}
//lamda style
Before(()->{});

Before hook is not visible to people who goes through only feature file. Alternatively you can use background more than Before. As it given more clarity to the non technical people.

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

Order in hook

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

@Before(order=2)
public void openBrowser(){}
@Before(order=5)
public void clearDataBase(){}
//using lamda
Before(2,()->{
openBrowser(){}
});
Before(5,()->{
clearDataBase(){}
});
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
@After
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 gets executed , AfterStep hook will also gets executed. In case if the step does not pass, its hooks will be ignored.

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

Tagged hook

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

Syntax of Tagged hook
@After(@mobileApp)
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.

Common use of hooks in code

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

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

@RunWith(cucumber.class)
@Cucumber.Options(format={"pretty","html:target/cucumber"})

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

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

Advantages of Hooks

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

Share and Enjoy !

7 thoughts on “What is Cucumber and How to Work With Cucumber?”

  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 https://mvnrepository.com/artifact/junit/junit/4.12 from https://www.techtravelhub.com/what-is-cucumber-how-to-work-with-cucumber/

    I would like to bring to your attention a resource I recently created – Guru99. https://www.guru99.com/download-installation-junit.html 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.

    Thanks!
    Alex

  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=============================

    Hi,

    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 https://mvnrepository.com/artifact/junit/junit/4.12 at your page https://www.techtravelhub.com/what-is-cucumber-how-to-work-with-cucumber/.

    I wouLd like to suggest an article I recently created which is more in-depth and well researched article https://www.guru99.com/download-installation-junit.html .

    I would be honoured if you link to it.

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

    Best,
    Alex

  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?

    Cheers

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

Leave a Comment

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