jeudi 24 août 2017

Spring mock performing post method and Controller redirection

My test:

@Test
public void shouldAddCompany() throws Exception {
    Company company = new Company("companyName", new Address());

Mockito.doReturn(company).when(companyServiceMock).save(any(Company.class));

    mockMvc.perform(post("/companies")
            .param("name", "companyName"))
            .andExpect(model().attribute("company",
                    hasProperty("name", is("companyName"))));
}

My controller:

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

There is an error:

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

it's because redirection and 302 status. When I change return in PostMapping to

return "companies";

the test passes, but I need this redirection. How can i fix that?

Aucun commentaire:

Enregistrer un commentaire