CucumberJVM: DataTable asMap() and asMaps()
What I learned today — 15 May 2018
Cucumber is a really nice tool for specification-by-example acceptance tests. The DataTable provides a convenient way supply parameters in a tabular format.
For brevity I’m going to use Kotlin data classes to define the DTO’s in the following examples:
The simple use of DataTable is to use headings that match the fields on a DTO.
Given the following cities exist:
| name | province | mayor |
| Johannesburg | Gauteng | Herman Mashaba |
| Cape Town | Western Cape | Patricia de Lille |
| Durban | Kwazulu-Natal | Zandile Gumede |
Letting Cucumber map that to a list of cities in the step definition is easy:
A DataTable can also contain two columns representing a single object.
When a city is updated:
| name | Cape Town |
| province | Western Cape |
| mayor | vacant |
These values can be read using the DataTable#asMap()
method, which interprets the first column as keys and the second column as values.
A DataTable with multiple rows can also be interpreted as a list of maps, using DataTable#asMaps()
. This could be useful, for example, if you wish to decouple your glue code (step definitions) from objects used in production code.
Then the cities have the following state:
| name | province | mayor |
| Johannesburg | Gauteng | Herman Mashaba |
| Cape Town | Western Cape | vacant |
| Durban | Kwazulu-Natal | Zandile Gumede |
In the step definition map each row (a map with the header row as keys and the row values as values) to the object of your choice:
One may also use these methods if Cucumber is unable to map the fields to the correct type on the DTO shown in the simple example.
Conclusion
I don’t know for how long Patricia de Lille will be able to stay in her office as mayor of Cape Town, but DataTable offers flexible ways to write feature specifications.