这是控制器中带注释的方法:
@RequestMapping(method = RequestMethod.GET)
public String getClient(@PathVariable("contractUuid") UUID contractUuid, Model model) {
ClientDto clientDto = new ClientDto();
clientDto.setContractUuid(contractUuid);
model.addAttribute("client", clientDto);
return "addClient";
}
@ModelAttribute("contract")
public ContractDto getContract(@PathVariable("contractUuid") UUID contractUuid) throws ContractNotFoundException {
return contractService.fromEntity(contractService.findByUuid(contractUuid));
}
我正在尝试的测试方法如下所示,但属性契约失败。属性客户端以@RequestMapping方法添加到模型中。
private MockMvc mockMvc;
@Autowired
private ContractService contractServiceMock;
@Autowired
private ClientService clientServiceMock;
@Autowired
protected WebApplicationContext wac;
@Before
public void setup() {
Mockito.reset(contractServiceMock);
Mockito.reset(clientServiceMock);
this.mockMvc = webAppContextSetup(this.wac).build();
}
@Test
public void test() throws Exception {
UUID uuid = UUID.randomUUID();
Contract contract = new Contract(uuid);
when(contractServiceMock.findByUuid(uuid)).thenReturn(contract);
mockMvc.perform(get("/addClient/{contractUuid}", uuid))
.andExpect(status().isOk())
.andExpect(view().name("addClient"))
.andExpect(forwardedUrl("/WEB-INF/pages/addClient.jsp"))
.andExpect(model().attributeExists("client"))
.andExpect(model().attributeExists("contract"));
}
当我运行应用程序时,合约属性显示在 jsp 页面中,因为我使用了它的一些属性,但由于它在测试方法中失败了,有没有另一种方法来测试它?它失败并显示以下消息:
java.lang.AssertionError:模型属性"contract"不存在
春天是 4.0.1.发布
看来是我的错。即使@ModelAttribute方法返回 ContractDto 的实例,我也只模拟了服务中使用的一种方法:
when(contractServiceMock.findByUuid(uuid)).thenReturn(contract);
所以 findByUuid 返回了一些东西,但 contractService.fromEntity 没有受到影响,所以我也不得不嘲笑它:
UUID uuid = UUID.randomUUID();
Contract contract = new Contract(uuid);
ContractDto contractDto = new ContractDto(uuid);
when(contractServiceMock.findByUuid(uuid)).thenReturn(contract);
when(contractServiceMock.fromEntity(contract)).thenReturn(contractDto);