7

我正在测试一个返回地图的控制器

@RequestMapping("/")
@ResponseBody
public Map<String, String> getMessages(@RequestBody String foo) {
    Map<String, String> map = boo.getMap(foo);
    return map;
}

测试:

...
resultActions
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(
                content().contentTypeCompatibleWith(
                        MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$", notNullValue()))
        .andExpect(jsonPath(EXPRESSION, equalsTo(foo));
 ...

我应该使用哪个表达式从 Map 中读取键和值?

编辑:解决它的一种方法可能是:

MvcResult result = resultActions.andReturn();
MockHttpServletResponse response = result.getResponse();
String content = response.getContentAsString();
Gson gson = new Gson();
Type typeOfT = new TypeToken<Map>() {
}.getType();
Map<String, String> map = gson.fromJson(content, typeOfT);

然后遍历地图检查值。但是有没有办法做到这一点jsonPath

4

1 回答 1

18

如果您使用的是 hamcrest Matchers,那非常容易。有两种方法可以获取地图条目的键或值。

  • Matchers.hasKey()

  • Matchers.hasValue()

还有一个简单的例子来检查结果 Map 中是否存在所有键。$.translationProperties直接指向地图。

 ResultActions resultActions = mvc.perform(...);
 List<String> languagesToBePresent = new ArrayList<>(); //add some values here

 for (String language : languagesToBePresent) {
            resultActions.andExpect(
                  jsonPath("$.translationProperties", Matchers.hasKey(language)));
        }
于 2015-06-26T12:22:08.220 回答