Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

java - Problem with deserialization of LocalDateTime in Junit test

I have problems LocalDateTime deserialization in Junit test. I have simple REST API which returns some DTO object. When I call my endpoint there is no problem with response - it is correct. Then I try to write unit test, obtain MvcResult and with use of ObjectMapper convert it to my DTO object. But I still receive:

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"])

I was trying with @JsonFormat and adding compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.9.8' to my build.gradle but I use Spring Boot 2.1.3.RELEASE so it is involved in it. I do not have any idea how to fix it. My simple endpoint and unit test below:

@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 class

public class MyDto {

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

// constructors, getters, setters
}

Unit test

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());
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You create new ObjectMapper in test class:

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

Try to inject ObjectMapper from Spring context or manually register module:

mapper.registerModule(new JavaTimeModule());

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...