[英]How to test a Controller, which retrieves data with Post method, using a MockMvc object?
Hello everyone I'm using Spring MVC framework and I want to test my Controllers. 大家好,我正在使用Spring MVC框架,并且我想测试我的控制器。 One of them uses the Post method in order to retrieve data from the View and I don't know how to to test it.
其中之一使用Post方法以便从View检索数据,但我不知道如何对其进行测试。
This is my Controller: 这是我的控制器:
@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";
}
And this is the test I tried which apparently doesn't work. 这是我尝试过的测试,显然不起作用。
@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"));
}
I think you want: 我想你要:
mockMvc.perform(post("/index").with(testSecurityContext())
.param("newLetter", lttr))
.andExpect(status().isOk())
.andExpect(model().attributeExists("allLetters"));
Note the param
instead of requestAttr
on the third line. 注意
param
而不是第三行的requestAttr
。 It's a parameter that you're looking for in your controller method, with the @RequestParam
annotation, not an attribute. 这是您要在控制器方法中寻找的参数,带有
@RequestParam
批注,而不是属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.