Pregunta

This are the annotated methods in the controller:

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

The test method that I am trying is shown below, but it fails for attribute contract. The attribute client is added to the Model in a @RequestMapping method.

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

The contract attribute shows in the jsp page when I run the application, since I use some of its attributes, but since it fails in the test method is there another way to test it ? It fails with the message:

java.lang.AssertionError: Model attribute 'contract' does not exist

Spring is 4.0.1.RELEASE

¿Fue útil?

Solución

It seems it was my fault. Even though the @ModelAttribute method returns an instance of ContractDto I only mocked one method used from the service:

when(contractServiceMock.findByUuid(uuid)).thenReturn(contract);

and so findByUuid returned something, but contractService.fromEntity was left untouched so I had to also mock it:

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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top