如何验证地图的值不为空

How can I verify that a map's values are not empty

假设我在 groovy 中指定了这样的合同:

org.springframework.cloud.contract.spec.Contract.make {
request {
    method "GET"
    url "/api/profiles"
    headers {
        header('Accept': 'application/json;charset=UTF-8')
        header('Content-Type': 'application/json;charset=UTF-8')
    }
}
response {
    status 200
    headers {
        header('Content-Type': 'application/json;charset=UTF-8')
    }
    body(
            value(
                    stub(
                            '''\
                    [
                      {
                        "profile": "profile1",
                        "myMap": {}
                      },
                      {
                        "profile": "profile2",
                        "myMap": {
                          "12345": "FOO",
                          "asdf": "BAR"
                        }
                      }
                    ]   
                    '''
                    ),
                    test(
                            [
                                    [
                                            "profile" : regex(nonEmpty()),
                                            "myMap": [
                                                         [
                                                            ??
                                                         ]
                                                      ]
                                    ]
                            ]
                    )
            )
    )
}

}

现在我想测试映射是否包含字符串到字符串条目,其中值不能为空。地图本身可能是空的。

如何测试动态键名?

在合同的响应端,您必须选择是使用地图表示法还是字符串表示法。如果你想对响应的片段进行断言,你必须将这些断言嵌入正文或使用测试匹配器。

您可以将正文作为多行字符串,然后编写 testMatchers 部分

testMatchers{
    jsonPath('$.[*].myMap', byCommand('assertKeys($it)'))
}

那么你在assertKeys方法中提供断言就足够了。