我有一个 Controller 映射
@RequestMapping(value = "/something", method = RequestMethod.GET)
public String get(@RequestParam("id") Person aPerson, Model aModel) {
aModel.addAttribute("person", aPerson);
return "index";
}
我如何通过 MockMvc 进行测试?
我可以做这样的事情
mockMvc.perform(get("/something?id=1")).andExpect(status().is2xxSuccessful());
但这不起作用,因为 RequestParam 是一个对象,而不是字符串。转换是由 Spring 完成的,但我正在对该方法进行单元测试,并且不想启动应用程序上下文。如何使用 MockMvc 进行单元测试?
最佳答案
你可以尝试类似的事情
@Test
public void test() throws Exception {
Model model= new Model();
mockMvc.perform(MockMvcRequestBuilders.get("/something?id=1")
.content(asJsonString(model))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)).andExpect(status().is2xxSuccessful());
}
关于java - 如何对具有对象的 RequestParam 的 Controller 方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55306901/