Issue
I have this in a cucumber step definition
secondIT.jsonPathEvaluator = secondIT.response.jsonPath();
Then in a different step def, where I assert, I have
public void employee_response_equals(DataTable responseFields){
List<Map<String,String>> fields = responseFields.asMaps(String.class,String.class);
Iterator<Map<String, String>> it = fields.iterator();
while (it.hasNext()) {
Map<String, String> map = it.next();
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
assertEquals(secondIT.jsonPathEvaluator.get(entry.getKey()), entry.getValue());
assertAll(
// how to use this instead
);
}
}
}
How do I use junit5 assertAll
to assert values that each of the key fetches(from jsonPathEvaluator
) and value from map
I tried to use assertEquals
but I am not sure if that is correct way as it prints only some information i.e this key = data.id
when I comment that line it prints everything
key = data.id
value = 2
key = data.employee_name
value = Garrett Winters
Also , I came across this but I am not sure how do I make executables for my scenario
sample data table:
And response includes the following employee info
|key |value|
| data.id | 3 |
| data.employee_name | Garrett Winters |
and sample response:
{
"status": "success",
"data": {
"id": 2,
"employee_name": "Garrett Winters",
"employee_salary": 170750,
"employee_age": 63,
"profile_image": ""
},
"message": "Successfully! Record has been fetched."
}
Solution
assertAll
is the wrong tool for the job. It only works if you know exactly how many things you want to assert and you can hard code these. You may instead want to look at using assertion library such as AssertJ.
Before using AssertJ the problem has to be simplified a bit.
You can remove the header from the data table in your step:
And response includes the following employee info
| data.id | 3 |
| data.employee_name | Garrett Winters |
Then can tell Cucumber you want this data as map by changing the DataTable to a map. Cucumber will tell you if it can't work out what you wanted.
@Then("response includes the following employee info")
public void employee_response_equals(Map<String, String> expectedFields){
Once you have the information as a map, you use the expected keys to collect all keys from the json response.
Map<String, Object> actualFields = expectedFields.keySet()
.stream()
.collect(Collectors.toMap(expectedKey -> expectedKey, expectedKey -> jsonPathEvaluator.get(expectedKey)));
Then you can use assertThat
from AssertJ to compare the two maps.
assertThat(actualFields).containsAllEntriesOf(expectedFields);
When the fields don't match up you'll get a nice message:
java.lang.AssertionError:
Expecting map:
<{"data.employee_name"="Nora Jones", "data.id"="3"}>
to contain:
<[data.id=3, data.employee_name=Garrett Winters]>
but could not find the following map entries:
<[data.employee_name=Garrett Winters]>
Answered By - M.P. Korstanje