使用jsonPath检查Map键/值

xed*_*edo 3 java jsonpath mockmvc

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

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

测试:

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

我应该使用哪个表达式来读取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);
Run Code Online (Sandbox Code Playgroud)

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

WeM*_*are 9

如果你正在使用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)));
        }
Run Code Online (Sandbox Code Playgroud)

  • `Matchers.hasEntry(K键,V值)`同样有用. (5认同)