如何使用预期的DTO测试控制器返回的JSON?

时间:2019-11-15 15:43:20

标签: java spring testing spring-test

我使用spring-test 5.0.7并遇到下一个问题:

DTO:

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

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

控制器:

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

测试失败:

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

测试日志:

java.lang.AssertionError: JSON path "$" 
Expected :TestTest.SomeDTO(uid=7817869a-eb9a-4491-a34b-a8006a643b6c, child=TestTest.AnotherDTO(someField=value))
Actual   :null

是否有任何方法可以使它工作而无需指定字段SomeDTO.child的类型?我猜这是行不通的,因为SomeDTO不提供有关字段child的信息(一旦我将其设为private AnotherDTO child,测试就会通过),但是可以在运行时进行计算。 / p>

0 个答案:

没有答案
相关问题