2

Hello everyone I'm using Spring MVC framework and I want to test my Controllers. 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.

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"));
}
nick
  • 1,611
  • 4
  • 20
  • 35

1 Answers1

3

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. It's a parameter that you're looking for in your controller method, with the @RequestParam annotation, not an attribute.

DaveyDaveDave
  • 9,821
  • 11
  • 64
  • 77