如何使用MockMvc对象测试使用Post方法检索数据的Controller?

时间:2015-12-14 14:46:38

标签: java spring spring-mvc spring-test-mvc

大家好,我使用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"));
}

1 个答案:

答案 0 :(得分:3)

我想你想要:

mockMvc.perform(post("/index").with(testSecurityContext())
                              .param("newLetter", lttr))
                              .andExpect(status().isOk())
                              .andExpect(model().attributeExists("allLetters"));

请注意第三行上的param而不是requestAttr。它是您在控制器方法中查找的参数,带有@RequestParam注释,而不是属性。