vendredi 15 novembre 2019

How to test JSON returned by controller using expected DTO?

I use spring-test 5.0.7 and run into the next issue:

DTOs:

@Data
@AllArgsConstructor
@NoArgsConstructor
public static class SomeDTO {
    private String uid;
    private Object child;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public static class AnotherDTO {
    private String someField;
}

Controller:

@RestController
@RequestMapping("/api")
public static class TestController {
    @GetMapping(path = "/dto/{uid}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public SomeDTO findSomeObject(@PathVariable String uid) {
        return new SomeDTO(uid, new AnotherDTO("value"));
    }
}

And a test that is failing:

@Test
public void testControllerResult() throws Exception {
    SomeDTO dto = new SomeDTO(UUID.randomUUID().toString(), new AnotherDTO("value"));

    mockMvc.perform(MockMvcRequestBuilders.get("/api/dto/{uid}", dto.getUid()))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$").value(dto));
}

Is there any way to make it working without specifying type of field SomeDTO.child? I guess it does not work because SomeDTO does not provide information about field child(as soon as I make it private AnotherDTO child, test will pass), but it can be calculated at runtime.

Aucun commentaire:

Enregistrer un commentaire