Junit测试中LocalDateTime反序列化的问题 [英] Problem with deserialization of LocalDateTime in Junit test
问题描述
在Junit
测试中,我在LocalDateTime
反序列化方面遇到问题.我有简单的REST API
,它返回一些DTO
对象.当我打电话给端点时,响应没有问题-是正确的.然后,我尝试编写单元测试,获取MvcResult
,并使用ObjectMapper
将其转换为我的DTO
对象.但我仍然收到:
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"])
我尝试使用@JsonFormat
并将compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.9.8'
添加到我的build.gradle
中,但是我使用的是Spring Boot 2.1.3.RELEASE
,所以它涉及其中.我不知道如何解决它.我的简单端点和单元测试如下:
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类
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());
}
}
推荐答案
您在测试中创建了新的ObjectMapper
:
You create new ObjectMapper
in test:
MyDto dto = new ObjectMapper().readValue(json, MyDto.class);
尝试从Spring
上下文中注入ObjectMapper
或手动注册模块:
Try to inject ObjectMapper
from Spring
context or manually register module:
mapper.registerModule(new JavaTimeModule());
在测试中.
另请参阅:
这篇关于Junit测试中LocalDateTime反序列化的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!