How to write a step definition for a single feature file with multiple scenarios in cucumber?
-
Say for example I have a feature file with 3 scenarios, in this how my step definition should be? Should I have one step definition written for all the scenarios? Or 3 step definition for 3 scenarios – Ashwini Arunachalam Sep 10 '19 at 11:22
-
One step definition is enough. – Mate Mrše Sep 10 '19 at 11:38
2 Answers
From Cucumber.io's page on Gherkin reference:
Feature: Guess the word
# The first example has two steps
Scenario: Maker starts a game
When the Maker starts a game
Then the Maker waits for a Breaker to join
# The second example has three steps
Scenario: Breaker joins a game
Given the Maker has started a game with the word "silky"
When the Breaker joins the Maker's game
And the Maker starts a game
Then the Breaker must guess a word with 5 characters
In the above example, the Maker starts a game
step will be implemented with something like
@When("the Maker starts a game")
public void theMakerStartsAGame(){
// implementation
}
In the above example, step definition will map to (recognize) both the When the Maker starts a game
and And the Maker starts a game
steps.
That step can be reused as many times as needed in all of the feature files inside of the folder defined under @CucumberOptions
.

- 7,997
- 10
- 40
- 77
-
Say for example I have a feature file with 3 scenarios, in this how my step definition should be? Should I have one step definition written for all the scenarios? Or 3 step definition for 3 scenarios – Ashwini Arunachalam Sep 10 '19 at 11:25
-
1 step in the gherkin scenario is related to 1 step definition. If you have already created the step definition, then no need to create it again - you could use the same step in the other scenarios. The steps are reusable. – Mr Cas Sep 10 '19 at 11:30
-
2@AshwiniArunachalam In the above example, step definition will map to (recognize) both the `When the Maker starts a game` and `And the Maker starts a game` steps. That step can be reused as many times as needed in all of the feature files inside of the folder defined under `@CucumberOptions`. – Mate Mrše Sep 10 '19 at 11:37
- Create feature file
Make sure you add correct paths to the features and step defs classes at @CucumberOptions in your cucumber runner class, such as:
@CucumberOptions( features = "src/test/resources/features", glue = "src/main/java/stepDefs" )
Write your step realization in step definitions package using cucumber annotations like @Given, @When etc.
@Given("Count {int} times") public void countMethod(int count) { }

- 743
- 1
- 5
- 19