使用 junit5 assertAll 来声明地图的黄瓜数据表列表

问题描述

我在黄瓜步骤定义中有这个

 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
                );
                    
                 }
             }
            
        }

如何使用 junit5 assertAll 来断言每个键获取的值(来自 jsonPathEvaluator)和来自地图的值

我尝试使用 assertEquals,但我不确定这是否是正确的方式,因为它只打印一些信息,即当我评论该行时,它会打印所有内容

key = data.id

另外,我遇​​到了 this,但我不确定如何为我的场景制作可执行文件

示例数据表:

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   |

解决方法

assertAll 是错误的工作工具。只有当你确切地知道你想要断言多少东西并且你可以对它们进行硬编码时,它才有效。您可能需要考虑使用断言库,例如 AssertJ

在使用 AssertJ 之前,必须稍微简化一下问题。

您可以在您的步骤中从数据表中删除标题:

    And response includes the following employee info
      | data.id            | 3               |
      | data.employee_name | Garrett Winters |

然后可以tell Cucumber you want this data as map by changing the DataTable to a map。 Cucumber 会告诉您它是否无法满足您的需求。

@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]>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...