Wednesday, November 30, 2016

How to Pass Examples Data As An Object In A Step Method Using Cucumber JVM

Still now whenever we use Scenario Outline we need to pass all parameters in a step method those are mentioned in glue code. So problem is if Examples section of Scenario Outline holds more parameters and also if our steps in feature file holds all the parameters then method argument count should be increased.

Now if we pass all parameters as a object then it becomes a single parameter on step method even if our feature steps holds lots of parameters. But there is a trick to make all this parameters as an object in step methods those are mentioned in feature steps.

So basically we mentioned our Example data to the feature step as Data Table.

So as an example :

Feature: This is a sample feature file

  Scenario Outline: This is a scenario to test datadriven test on Cucumber JVM.
    Given scenario data
    When executed from Runner Class.
    Then UserName and Password shows on console from Examples "<username>" and "<password>"
    Then UserName and Password shows on console with header as:
      | username     | password     |
      | "<username>" | "<password>" |
    Then UserName and Password shows on console without header as:
      | "<username>" | "<password>" |

      | username        | password        |
      | Test UserName 1 | Test Password 1 |
      | Test UserName 2 | Test Password 2 |

So Glue Code is 

@Then("^UserName and Password shows on console from Examples \"([^\"]*)\" and \"([^\"]*)\"$")
public void usernameAndPasswordShowsOnConsoleFromExamplesAnd(String userName, String password) throws Throwable {
System.out.println("UserName : " + userName + " Password : " + password);

@Then("^UserName and Password shows on console with header as:$")
public void usernameAndPasswordShowsOnConsoleWithHeaderAs(List<ExampleData> data) throws Throwable {
System.out.println("UserName : " + data.get(0).getUsername() + " Password : " + data.get(0).getPassword());

@Then("^UserName and Password shows on console without header as:$")
public void usernameAndPasswordShowsOnConsoleWithoutHeaderAs(List<String> stringData) throws Throwable {
System.out.println("UserName : " + stringData.get(0) + " Password : " + stringData.get(1));

class ExampleData{
private String username;
private String password;
public String getUsername() {
return username;
public void setUsername(String username) {
this.username = username;
public String getPassword() {
return password;
public void setPassword(String password) {
this.password = password;


 So if we drill down our code we can observe that when we mentioned the header of Examples below the feature steps we need to Create data object class in glue code to use it.

If user don't want to create any dataclass for that then user cannot mention the header name below the steps.