-2

How to write a step definition for a single feature file with multiple scenarios in cucumber?

Mate Mrše
  • 7,997
  • 10
  • 40
  • 77

2 Answers2

2

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.

Mate Mrše
  • 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
0
  1. Create feature file
  2. 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" )

  3. Write your step realization in step definitions package using cucumber annotations like @Given, @When etc.

    @Given("Count {int} times") public void countMethod(int count) { }

Vault23
  • 743
  • 1
  • 5
  • 19