tony
tony

Reputation: 1651

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. 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"));
}

Upvotes: 2

Views: 1760

Answers (1)

DaveyDaveDave
DaveyDaveDave

Reputation: 10612

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.

Upvotes: 3

Related Questions