[英]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.