我在黄瓜步骤定义中有这个
secondIT.jsonPathEvaluator = secondIT.response.jsonPath();
然后在另一个步骤def中,我断言,我有
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
);
}
}
}
如何使用junit5assertAll
来断言每个键(从jsonPathEvaluator
)获取的值和从map
获取的值我尝试使用assertEquals
,但我不确定这是否是正确的方式,因为它只打印一些信息,即这个key = data.id
,当我注释那行时,它打印一切
key = data.id
value = 2
key = data.employee_name
value = Garrett Winters
同样,我遇到了这个,但我不确定我如何为我的场景制作可执行文件
示例数据表:
And response includes the following employee info
|key |value|
| data.id | 3 |
| data.employee_name | Garrett Winters |
和样本回答:
{
"status": "success",
"data": {
"id": 2,
"employee_name": "Garrett Winters",
"employee_salary": 170750,
"employee_age": 63,
"profile_image": ""
},
"message": "Successfully! Record has been fetched."
}
assertAll
是错误的工具。只有当您确切地知道要断言多少东西并且可以对这些东西进行硬编码时,它才会起作用。相反,您可能想看看使用断言库,如AssertJ。
在使用AssertJ之前,这个问题必须稍微简化一下。
您可以在步骤中从数据表中删除标题:
And response includes the following employee info
| data.id | 3 |
| data.employee_name | Garrett Winters |
然后可以通过将DataTable更改为map来告诉Cucumber您希望此数据为map。黄瓜会告诉你,如果它不能完成你想要的。
@Then("response includes the following employee info")
public void employee_response_equals(Map<String, String> expectedFields){
一旦将信息作为映射,就可以使用期望的键从json响应中收集所有键。
Map<String, Object> actualFields = expectedFields.keySet()
.stream()
.collect(Collectors.toMap(expectedKey -> expectedKey, expectedKey -> jsonPathEvaluator.get(expectedKey)));
然后你可以使用AssertJ中的assertThat
来比较两个映射
assertThat(actualFields).containsAllEntriesOf(expectedFields);
当字段不匹配时,你会得到一个很好的消息:
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]>