mercredi 23 août 2017

Spring MVC test post method with controller redirect

I have a test:

@Test
public void shouldAddCompany() throws Exception {
    mockMvc.perform(post("/companies")
            .param("name", "companyName"))
            .andExpect(model().attribute("company",
                    hasProperty("name", is("companyName"))));

}

and my controller method looks like that:

@PostMapping("/companies")
public String displayCompaniesPost(@ModelAttribute Company company) {
    companyService.save(company);
    return "redirect:/companies";
}

How can i check company attribute in test? There is a problem because of redirect and status 302.

 java.lang.AssertionError: Model attribute 'company'
 Expected: hasProperty("name", is "companyName")
 but: was null

I think it occurs because controller is going to GET method because of redirection. When I remove this redirection everything is ok, but I don't want to remove that redirection.

Aucun commentaire:

Enregistrer un commentaire