简体   繁体   English

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

[英]How to test with MockMVC a Map parameter in Spring Rest

In Spring Rest , I have a RestController exposing this method:Spring Rest 中,我有一个RestController公开这个方法:

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

I'd like to have this method tested, using MockMVC from Spring :我想使用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());

The problem is I get a 500 HTTP error code .问题是我收到了500 HTTP 错误代码 I'm pretty sure this comes from the fact that I use a Map as a parameter of my controller (I tried changing it to String and it works).我很确定这是因为我使用Map作为控制器的参数(我尝试将其更改为 String 并且它有效)。

The question is: How can I do to have a Map in parameter in my RestController , and test it correctly using MockMVC ?问题是:如何在我的RestController参数中有一个Map ,并使用MockMVC正确测试它?

Thanks for any help.谢谢你的帮助。

I know this is an old post but I came across the same problem and I ended up solving it as follows:我知道这是一篇旧帖子,但我遇到了同样的问题,最终解决了以下问题:

My controller was ( Check that RequestParam has no name ):我的控制器是(检查 RequestParam 没有名字):

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

In my unit test I did:在我的单元测试中,我做了:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM