[英]How to test a Controller, which retrieves data with Post method, using a MockMvc object?
大家好,我正在使用Spring MVC框架,并且我想测试我的控制器。 其中之一使用Post方法以便从View检索数据,但我不知道如何对其进行测试。
这是我的控制器:
@RequestMapping(value="/index", method=RequestMethod.POST)
public String postMessage(@RequestParam("newLetter") String lttr, Model model)
{
Letter newLetter = lttr;
this.letterService.insertLetter(newLetter);
this.allLetters = this.letterService.getAllLetters();
model.addAttribute("allLetters", this.allLetters);
return "redirect:/index";
}
这是我尝试过的测试,显然不起作用。
@Test
@WithMockUser("randomUser")
public void aTest() throws Exception
{
Letter lttr = new Letter();
mockMvc.perform(post("/index").with(testSecurityContext()))
.andExpect(status().isOk())
.requestAttr("newLetter", lttr)
.andExpect(model().attributeExists("allLetters"));
}
我想你要:
mockMvc.perform(post("/index").with(testSecurityContext())
.param("newLetter", lttr))
.andExpect(status().isOk())
.andExpect(model().attributeExists("allLetters"));
注意param
而不是第三行的requestAttr
。 这是您要在控制器方法中寻找的参数,带有@RequestParam
批注,而不是属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.