Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test with MockMVC a Map parameter in Spring Rest

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.

like image 232
Rémi Doolaeghe Avatar asked Oct 01 '15 10:10

Rémi Doolaeghe


1 Answers

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();      
like image 89
Daniela Avatar answered Sep 28 '22 17:09

Daniela