Prashant Bhardwaj
Prashant Bhardwaj

Reputation: 176

How to map gherkin step definition data to a Java object in Cucumber?

I have following three classes:

class City {
 String name;
 String code;
}

class Address {
 String street;
 City city;
}

class Person {
 String name;
 int age;
 Address address;
}

Now, I have a REST API to POST a person.

POST /person

{
 "name":"John",
 "age":21,
 "address":{
  "street":"First st.",
  "city":{
   "name":"London"
  }
 }
}

To test this API, I created a scenario using Cucumber and within that created following step definition:

Then a person is created using REST api "/person"
| name | age | address.street | address.city.name |
| John | 21  | First st.      | London            |

In my Java class, created following method to map this step onto it:

public void create_a_person(Person person){
 System.out.println("Person - " + person);
}

This code is unable to create a person object using the data given in the step. It throws following exception:

cucumber.runtime.CucumberException: Not a Map or List type: class Person

However, it easily creates Person object, if data is given like:

Then a person is created using REST api "/person"
| name | age |
| John | 21  | 

Any idea, how can Cucumber map step data onto child member variables (like Address and City in this case)?

Upvotes: 3

Views: 3689

Answers (1)

Len
Len

Reputation: 2145

I think you'll find your answer here: https://github.com/cucumber/cucumber/tree/master/datatable#custom-table-types. You'll need to implement a TableTransformer.

Tables are a bit of an 'odd' data type in cucumber, e.g. compared to other +custom data types, that live in cucumber expressions

Upvotes: 2

Related Questions