【问题标题】:Problem with deserialization of LocalDateTime in Junit testJunit测试中LocalDateTime反序列化的问题
【发布时间】:2019-08-02 02:31:47
【问题描述】:

我在Junit 测试中遇到LocalDateTime 反序列化问题。我有简单的REST API,它返回一些DTO 对象。当我调用我的端点时,响应没有问题 - 这是正确的。然后我尝试编写单元测试,获取MvcResult 并使用ObjectMapper 将其转换为我的DTO 对象。但我仍然收到:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.time.LocalDateTime` out of START_ARRAY token
 at [Source: (String)"{"name":"Test name","firstDate":[2019,3,11,18,34,43,52217600],"secondDate":[2019,3,11,19,34,43,54219000]}"; line: 1, column: 33] (through reference chain: com.mylocaldatetimeexample.MyDto["firstDate"])

我正在尝试使用@JsonFormat 并将compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.9.8' 添加到我的build.gradle 但我使用Spring Boot 2.1.3.RELEASE 所以它参与其中。我不知道如何解决它。下面是我的简单端点和单元测试:

@RestController
@RequestMapping("/api/myexample")
public class MyController {

    @GetMapping("{id}")
    public ResponseEntity<MyDto> findById(@PathVariable Long id) {

        MyDto myDto = new MyDto("Test name", LocalDateTime.now(), LocalDateTime.now().plusHours(1));
        return ResponseEntity.ok(myDto);
    }
}

MyDto 类

public class MyDto {

    private String name;
    private LocalDateTime firstDate;
    private LocalDateTime secondDate;

// constructors, getters, setters
}

单元测试

public class MyControllerTest {

    @Test
    public void getMethod() throws Exception {
        MyController controller = new MyController();
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build();

        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/myexample/1"))
                .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();

        String json = mvcResult.getResponse().getContentAsString();
        MyDto dto = new ObjectMapper().readValue(json, MyDto.class);

        assertEquals("name", dto.getName());
    }
}

【问题讨论】:

    标签: java spring-boot junit jackson


    【解决方案1】:

    您在测试类中创建新的ObjectMapper

    MyDto dto = new ObjectMapper().readValue(json, MyDto.class);
    

    尝试从Spring上下文注入ObjectMapper或手动注册模块:

    mapper.registerModule(new JavaTimeModule());
    

    另见:

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 2018-07-15
      • 2023-03-03
      相关资源
      最近更新 更多