Spring模拟执行post方法和Controller重定向

时间:2017-08-24 11:12:09

标签: java spring spring-mvc testing mocking

我的测试:

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

我的控制器:

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

有一个错误:

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

它是因为重定向和302状态。当我将PostMapping中的return更改为

return "companies";

测试通过,但我需要这个重定向。我该如何解决这个问题?

0 个答案:

没有答案