如何在Spring Rest中使用MockMVC测试Map参数

Rém*_*ghe 6 java dictionary mockmvc spring-restcontroller

Spring Rest中,我有一个RestController公开这个方法:

@RestController
@RequestMapping("/controllerPath")
public class MyController{
    @RequestMapping(method = RequestMethod.POST)
    public void create(@RequestParameter("myParam") Map<String, String> myMap) {
         //do something
    }
}
Run Code Online (Sandbox Code Playgroud)

我想有这样的方法进行测试,使用MockMVC:

// 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());
Run Code Online (Sandbox Code Playgroud)

问题是我得到500 HTTP错误代码.我很确定这是因为我使用Map作为我的控制器的参数(我尝试将其更改为String并且它可以工作).

问题是:如何在我的RestController中使用Map参数,并使用MockMVC正确测试?

谢谢你的帮助.

Dan*_*ela 5

我知道这是一篇旧帖子,但我遇到了同样的问题,最终解决如下:

我的控制器是(检查 RequestParam 没有名称):

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

在我的单元测试中我做了:

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();      
Run Code Online (Sandbox Code Playgroud)