我在測試中反序列化時遇到問題。我有簡單的返回一些對象。當我調用我的端點時,響應沒有問題 - 它是正確的。然后我嘗試編寫單元測試,獲取并使用它轉換為我的對象。但我仍然收到:LocalDateTimeJunitREST APIDTOMvcResultObjectMapperDTOcom.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"])我正在嘗試并添加到我的,但我使用所以它參與其中。我不知道如何解決它。我下面的簡單端點和單元測試:@JsonFormatcompile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.9.8'build.gradleSpring 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); }}我的課程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()); }}
1 回答

慕容森
TA貢獻1853條經驗 獲得超18個贊
在測試類中創建新的:ObjectMapper
MyDto dto = new ObjectMapper().readValue(json, MyDto.class);
嘗試從上下文注入或手動注冊模塊:ObjectMapper
Spring
mapper.registerModule(new JavaTimeModule());
另請參閱:
添加回答
舉報
0/150
提交
取消