Step Definitions

Step Definitions are bits of code that make your scenarios in Cucumber come to life. They connect the plain-language steps in your scenarios to the actual code that runs when those steps are executed.


Each step written in Gherkin syntax (Given, When, Then, etc.) needs a corresponding Step Definition, which tells Cucumber what to do when it encounters that step.


Step Definitions are written in a programming language like Java, JavaScript, Ruby, Python, etc. They describe the actions or verifications to be performed when a step is executed.


Following is an example of feature file.


Gherkin
Copy
Given the user is on the login page
When the user enters valid credentials
Then the user should be logged in successfully


Following is an example of step definition file.


Java
Copy
    @Given("Website home page is open")
    public void website_home_page_is_open() {
        System.out.println("This is Given");
    }

    @When("User click on Request Call link")
    public void user_click_on_request_call_link() {
        System.out.println("This is When");
    }

    @Then("Request Call page should open")
    public void request_call_page_should_open() {
        System.out.println("This is Then");
    }

In the above example, you can see the value of each keyword under scenario section of the feature file matches the value of the step definition annotation. For example, statement of Given in feature file is mapped to a function with annotation @Given, statement of When is mapped to a function with annotation @When, statement of Then is mapped to a function with annotation @Then. This is how the cucumber will map each step definition function to the Gherkin step.


Each Step Definition method contains the actual code that interacts with the software, like clicking buttons, entering text, or verifying outcomes.


Step Definitions are the link between the plain-text scenarios and the code that makes your software do what your scenarios say.

Tips:

Create the feature file first and then run the feature file, the step definition functions will be printed in the console. You can copy paste those functions to your step definition file.