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

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

Posted by: admin August 10, 2018 Leave a comment

Questions:

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)?

Answers: