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
?
JSONPath is a query language for JSON, similar to XPath for XML. It allows you to select and extract data from a JSON document. You use a JSONPath expression to traverse the path to an element in the JSON structure.
A JSONPath expression specifies a path to an element (or a set of elements) in a JSON structure. Paths can use the dot notation: $.store.book[0].title. or the bracket notation: $['store']['book'][0]['title']
: operator is the array slice operator, so you can slice collections using the syntax [start:end:step] to return a subcollection of a collection. ( ) operator lets you pass a script expression in the underlying implementation's script language. It's not supported by every implementation of JSONPath, however.
JsonPath is an alternative to using XPath for easily getting values from a Object document. It follows the Groovy dot notation syntax when getting an object from the document. You can regard it as an alternative to XPath for XML.
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)));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With