How to check map parameter in Spring Rest using MockMVC

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 want to test this method 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 that I received a 500 HTTP error code . I am pretty sure that this is due to the fact that I use Map as a parameter of my controller (I tried changing it to String, and it works).

The question is how to make the Map in parameter be in my RestController and correctly test it with MockMVC ?

Thanks for any help.

+6
1

, , :

:

@GetMapping
public ResponseEntity findUsers (@RequestParam final Map<String, String> parameters) {
//controller code
}

:

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();      
+1

Source: https://habr.com/ru/post/1609780/


All Articles