Step Definition in Cucumber
The previous tutorial explained the Feature File in Cucumber. This tutorial explains the step definition in the Cucumber.
To start with, please add the below dependencies to the POM.xml, in the case of the Maven project.
io.cucumber cucumber-java 6.11.0 io.cucumber cucumber-junit 6.11.0 test junit junit 4.13.2 test
For the Gradle project, add the below dependencies to build.gradle
implementation 'io.cucumber:cucumber-java:6.11.0' testImplementation 'io.cucumber:cucumber-junit:6.11.0' testImplementation 'junit:junit:4.13.2'
What is Step Definition?
A Step Definition is a Java method with an expression that links it to one or more Gherkin steps. When Cucumber executes a Gherkin step in a scenario, it will look for a matching step definition to execute.
Cucumber finds the Step Definition file with the help of the Glue code in Cucumber Options.
By storing state in instance variables, a step definition can transfer state to a subsequent step definition.
Step definitions are not associated with a specific feature file or scenario. The name of a step definition’s file, class, or package has no bearing on which Gherkin steps it will match. The formulation of the step definition is the only thing that matters, which means the step definition should only match Gherkin’s steps.
Imagine, we want to test a web application. One of the first steps is Login to the website and then check the various functionalities on the website. We can create a Gherkin step like “I login to the website” and the corresponding step definition of this Gherkin Step. This Gherkin step can be used in multiple feature files, and we don’t need to create the step definition of this Gherkin step for each feature file.
In the previous tutorial, we have seen that when the Feature file is executed without the Step Definition file, the runner shows the missing steps with the snippet in the console.
When Cucumber encounters a Gherkin step without a matching step definition, it will print a step definition snippet with a matching Cucumber Expression. You can use this as a starting point for new step definitions.
It is very easy to implement all the steps, all you need to do is to copy the complete text marked in the above box and paste it into the MyHolidayDefinitions class.
@Given, @When, and @Then are imported from packages:-
import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When;
Feature File
Feature: Book flight ticket @BookOneWayFlight Scenario: Book Flight for one way trip Given I live in Dublin with 2 adults and 2 kids And I want to book one way flight ticket from Dublin to London on 22 Jan 2020 When I search online Then TripAdvisor should provide me options of flights on 22 Jan 2020 And Cost of my flight should not be more than 50 Euro per person And Tickets should be refundable
Let me create the step definition for the above Feature file
import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; public class MyHolidayDefinitions < @Given("I live in Dublin with adults and kids") public void liveInDublin(Integer int1, Integer int2) < System.out.println("I live in Dublin with 2 adults and 2 kids"); >@Given("I want to book one way flight ticket from Dublin to London on Jan ") public void bookFlightTicket(Integer int1, Integer int2) < System.out.println("I want to book one way flight ticket from Dublin to London on 22 Jan 2020"); >@When("I search online") public void searchOnline() < System.out.println("I search online"); >@Then("TripAdvisor should provide me options of flights on Jan ") public void tripAdvisor(Integer int1, Integer int2) < System.out.println("TripAdvisor should provide me options of flights on 22 Jan 2020"); >@Then("Cost of my flight should not be more than Euro per person") public void costOfFlightLimit(Integer int1) < System.out.println("Cost of my flight should not be more than 50 Euro per person"); >@Then("Tickets should be refundable") public void refundableTickets() < System.out.println("Tickets should be refundable"); >>
To run the scenarios present in the Feature File, we need TestRunner class. To know more about the TestRunner class, please refer to this tutorial –
import org.junit.runner.RunWith; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; @RunWith(Cucumber.class) @CucumberOptions(features = «src/test/resources/Features/MyHoliday.feature», tags = «@BookOneWayFlight», glue = «com.cucumber.MyCucumberProject.definitions») public class CucumberRunnerTest
The output of the above program is
Congratulations. We have created the setup definition for the feature file successfully and are able to run it.
Happy Learning!!
Step Organization
You can have all of your step definitions in one file, or in multiple files. When you start with your project, all your step definitions will probably be in one file. As your project grows, you should split your step definitions into meaningful groups in different files. This will make your project more logical and easier to maintain.
How Cucumber finds your features and step definitions
Be aware that, regardless of the directory structure employed, Cucumber effectively flattens the features/ directory tree when running tests. This means that anything ending in .java .kt .js .rb .go inside the directory in which Cucumber is run is treated as a step definition. In the same directory, Cucumber will search for a Feature corresponding to that step definition. This is either the default case or the location specified with the relevant relevant relevant -r relevant option.
Grouping step definitions
Technically it doesn’t matter how you name your step definition files, or which step definitions you put in a file. You could have one giant file containing all your step definitions. However, as the project grows, the file can become messy and hard to maintain. Instead, we recommend creating a separate *_steps.rb StepDefinitions.java StepDefinitions.kt *_steps.js *_steps.go file for each domain concept.
A good rule of thumb is to have one file for each major model/database table. domain object. domain object. domain object. domain object.
For example, in a Curriculum Vitae application, we might have:
- employee_steps.rb
- education_steps.rb
- experience_steps.rb
- authentication_steps.rb
- EmployeeStepDefinitions.java
- EducationStepDefinitions.java
- ExperienceStepDefinitions.java
- AuthenticationStepDefinitions.java
- EmployeeStepDefinitions.kt
- EducationStepDefinitions.kt
- ExperienceStepDefinitions.kt
- AuthenticationStepDefinitions.kt
- employee_steps.js
- education_steps.js
- experience_steps.js
- authentication_steps.js
- employee_steps.go
- education_steps.go
- experience_steps.go
- authentication_steps.go
The first three files would define all the Given , When , and Then step definitions related to creating, reading, updating, and deleting the various models. types of objects. types of objects. types of objects. The last file would define step definitions related to logging in and out, and the different things a certain user is allowed to do in the system.
If you follow this pattern, you also avoid the Feature-coupled step definitions anti-pattern.
Of course, how you group your step definitions is really up to you and your team. They should be grouped in a way that is meaningful to your project.
Writing step definitions
Don’t write step definitions for steps that are not present in one of your scenarios. These might end up as unused cruft that will need to be cleaned up later. Only implement step definitions that you actually need. You can always refactor your code as your project grows.
Avoid duplication
Avoid writing similar step definitions, as they can lead to clutter. While documenting your steps helps, making use of helper methods to abstract them can do wonders.
For example, take the following steps:
Given I go to the home page Given I check the about page of the website Given I get the contact details
If all of these steps open their respective web pages, you might be writing redundant steps. While the underlying code for these steps could be different, their behaviour is essentially the same, i.e. to open the Home, About or Contact page.
As such, you can use abstract helper methods to reduce them into a single step:
And the following step definition:
@Given("I go to the page") public void i_want_to_open_page(String webpage)
Given("I go to the page", function (webpage)
Given 'I go to the page' do |page| open_web_page page end
@Given("I go to the page") fun `I want to open page`(webpage: String)
s.Step(`^I go to the "([^"]*)" page$`, goToPage) func goToPage(webpage string) error
Your step definitions are the glue to the actual code (in this example, a factory method to decide which page to open). They can also be used to hide implementation details by calling several reusable helper methods from one step definition.
This helps in a number of ways:
- Increased maintainability.
- Increased scalability with reusable steps.
- More understandable tests.
You can handle other behaviours, like validating a web page, clicking a button, etc., the same way.
We suggest taking a look at the Factory Design Pattern as well. We suggest taking a look at the Factory Design Pattern as well. We suggest taking a look at the Factory Design Pattern as well. Also, using Data Tables for providing inputs to steps helps increase maintainability and understandability.
Helper methods
Always keep in mind that Cucumber is a DSL wrapper around the programming language whose full expressiveness remains available to you in the step definition files (but not in feature files). On the other hand, do not lose sight that every step called as such in a step definition file is first parsed by Gherkin and therefore must conform to the same syntax as used in feature files.
In fact, it is recommended to refactor step definitions into helper methods for greater modularity and reuse. The method can reside in the same .java .kt .js .rb .go file as the step definition.
This makes your project more understandable for people who join your project at a later date; which also makes your project easier to maintain.
You can help us improve this documentation. Edit this page.