Check Map key/values with jsonPath

xedo picture xedo · May 1, 2015 · Viewed 12.7k times · Source

I'm testing a controller that returns a Map

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

Test:

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

Which expression should I use to read the key and the value from the Map?

Edit: A way around to solve it could be:

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

And then loop through the map checking the values. But is there a way to do it with jsonPath?

Answer

WeMakeSoftware picture WeMakeSoftware · Jun 26, 2015

If you're using hamcrest Matchers that's pretty easy. There are two methods to get your hands on either key or value of the map entry.

  • Matchers.hasKey()

  • Matchers.hasValue()

And a simple example to check if all keys are present in the resulting Map. $.translationProperties directly points to the map.

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

 for (String language : languagesToBePresent) {
            resultActions.andExpect(
                  jsonPath("$.translationProperties", Matchers.hasKey(language)));
        }