In Spring Rest, I have a RestController exposing this method:
@RestController
@RequestMapping("/controllerPath")
public class MyController{
@RequestMapping(method = RequestMethod.POST)
public void create(@RequestParameter("myParam") Map<String, String> myMap) {
//do something
}
}
I'd like to have this method tested, using MockMVC from Spring:
// Initialize the map
Map<String, String> myMap = init();
// JSONify the map
ObjectMapper mapper = new ObjectMapper();
String jsonMap = mapper.writeValueAsString(myMap);
// Perform the REST call
mockMvc.perform(post("/controllerPath")
.param("myParam", jsonMap)
.andExpect(status().isOk());
The problem is I get a 500 HTTP error code. I'm pretty sure this comes from the fact that I use a Map as a parameter of my controller (I tried changing it to String and it works).
The question is: How can I do to have a Map in parameter in my RestController, and test it correctly using MockMVC?
Thanks for any help.
I know this is an old post but I came across the same problem and I ended up solving it as follows:
My controller was (Check that RequestParam has no name):
@GetMapping
public ResponseEntity findUsers (@RequestParam final Map<String, String> parameters) {
//controller code
}
In my unit test I did:
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.put("name", Collections.singletonList("test"));
parameters.put("enabled", Collections.singletonList("true"));
final MvcResult result = mvc.perform(get("/users/")
.params(parameters)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn();
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