Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of Cucumber DataTable to Map

I am using Cucumber Data Tables. I want to convert this Data Table into a Map rather than a list. So basically what if I use the Header Row as Key and the data rows as value for the key. How should I do that?

Let me share 1 example to be more clear.

Given the following animals:

  | Type  | BabyAnimal |    
  | cow   | Calf       |
  | horse | Pony       |
  | sheep | Lamb       |

Instead of creating a List<List<String>> here, it is a better approach to use a List<Map<String,String>> here. Map's Key should contain 'Type' and 'BabyAnimal' and values should contain the respective values. So the Map entities would be:

<Type,cow>,<BabyAnimal,Calf>
<Type,horse>,<BabyAnimal,Pony>
<Type,sheep>,<BabyAnimal,Lamb>

How would we do that? I feel this is a better approach of doing because we are fetching the data from the keys. eg List(1).Map.get(Type) Whereas in case of List we would have to do a get(0), get(1) and there are chances of using incorrect data.

like image 277
Neha Avatar asked Jun 18 '18 10:06

Neha


2 Answers

And adding a second answer because the generic types in your question got munched by the html.

Given the following animals:

| Type  | BabyAnimal |    
| cow   | Calf       |
| horse | Pony       |
| sheep | Lamb       |

And assuming you want this to be your step definition:

@Given("all baby animal details")
public void allMapDetails(List<Map<String, String>> animals) {
    System.out.println(animals);
}

Then the table will be automatically converted to a list of maps of string to string.

like image 163
M.P. Korstanje Avatar answered Nov 17 '22 13:11

M.P. Korstanje


Perhaps the API has moved on since this question was first posted. I'm using cucumber version 4.8.1 and this code gives what you need without the cumbersome Lists of Maps

Map<String, String> map = dataTable.asMap(String.class, String.class);
like image 22
Brad Avatar answered Nov 17 '22 13:11

Brad