7

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

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

我想使用Spring中的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());

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

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

谢谢你的帮助。

4

1 回答 1

5

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

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

@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();      
于 2019-08-09T00:31:34.347 回答