![](/img/trans.png)
[英]Spring boot patch request on controller with Map parameter. Test with mockmvc
[英]How to test with MockMVC a Map parameter in Spring Rest
在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 ,并使用MockMVC正确测试它?
谢谢你的帮助。
我知道这是一篇旧帖子,但我遇到了同样的问题,最终解决了以下问题:
我的控制器是(检查 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.