Skip to main content

Cucumber with Java: Steps & Step Definition

A feature file has many Steps, and each Step has a Step Definition associated with it. When Cucumber executes a Step in a Scenario it look for a matching Step Definition to execute. Step Definitions are also known as Glue Code.

Step Definitions are written inside a class file. Right click on your package and create new class file with name you like.

Here is the sample feature file consist of single scenario and 2 steps starting with When and Then keyword, copy below code and paste it to your feature file:

@search
Feature: Search
  I want to search the website

  @smoke
  Scenario: Keyword Search
    When I filled in "Search Textbox" with "dress" on "Home" page
    Then I click "Search Button" on "Home" page

Now, you have to write your Step Definition inside this file. Eclipse Cucumber plugin help you to generate Step Definition automatically, all you have to do is run the feature file.

There are several methods to run feature file, for now just right click on you feature file and click Run As -> Cucumber Feature.

After running the feature file you will see below code in Eclipse console, These are Cucumber Step Definitions which Cucumber auto generate:

1 Scenarios (1 undefined)
2 Steps (2 undefined)
0m4.783s


You can implement missing steps with the snippets below:

@When("^I filled in \"([^\"]*)\" with \"([^\"]*)\" on \"([^\"]*)\" page$")
public void i_filled_in_with_on_page(String arg1, String arg2, String arg3) {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I click \"([^\"]*)\" on \"([^\"]*)\" page$")
public void i_click_on_page(String arg1, String arg2) {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

You can see 1 scenario is executed and it has 2 Steps and both are undefined and we have suggestion that we can implement missing steps. Copy paste code snippet starting with @When and @Then to Step Definition file.

Next step is comment or delete line starting with throw keyword. Now execute your feature file again, you will not receive any error. You can place your selenium or java code inside this methods.

In Our JUnit Test Runner Class, insider Cucumber Options, we specify path for glue code. When Cucumber starts execution, it looks for classes in Path mentioned in glue code.

In above code @Given, @When and @Then are Cucumber annotations. There is text inside (" ") which cucumber matches with your steps written in Feature file. After the match found Cucumber executed the method associated with it. If a match is not found Cucumber will return Undefined Steps error.

Video Tutorial

About

Elix is a premium wordpress theme for portfolio, freelancer, design agencies and a wide range of other design institutions.