Jackson.InvalidDefinitionException: 无法在 JUnit @BeforeEach 中构造 java.time.OffsetDateTime 的实例

Jackson.InvalidDefinitionException: Cannot construct instance of java.time.OffsetDateTime in JUnit @BeforeEach

我正在尝试为我的 Open-API 自动生成的代码创建单元测试用例。我有一个 date-time 格式,它在 API 中工作正常,但当我尝试设置我的 JUnit 测试用例时失败

JUnit 设置代码:

@BeforeEach
public void setUp() throws IOException {
        MockitoAnnotations.initMocks(this);
        requestDTO = objectMapper.readValue(TestData.TEST_JSON, RequestDTO.class);
    }

TestData.TEST_JSON :

public static String TEST_JSON= "{\n" +
            "  \"name\": \"credit_application\",\n" +
            "  \"comments\": {\n" +
            "    \"id\": \"1\",\n" +
            "    \"userId\": \"21212\",\n" +
            "    \"taskId\": \"212\",\n" +
            "    \"time\": \"2010-07-17T02:49:58.564Z\",\n" +
            "    \"comment\": \"Hello world\"\n" +
            "  },\n" +
            "  \"id\": \"123\",\n" +
            "  \"version\": \"1.0\"\n" +
            "}";

/*
{
  "name": "credit_application",
  "comments": {
    "id": "1",
    "userId": "21212",
    "taskId": "212",
    "time": "2010-07-17T02:49:58.564Z",
    "comment": "Hello world"
  },
  "id": "123",
  "version": "1.0"
}
*/

RequestDTO(打开-API自动生成的代码):

public class RequestDTO   {
  @JsonProperty("name")
  private String name;

  @JsonProperty("comments")
  private CommentDTO comments;

  @JsonProperty("id")
  private String id;

  // Constructors and Getters/Setters

}

CommentDTO(打开-API自动生成的代码):

public class CommentDTO   {
  @JsonProperty("id")
  private String id;

  @JsonProperty("userId")
  private String userId;

  @JsonProperty("taskId")
  private String taskId;

  @JsonProperty("time")
  private OffsetDateTime time;

  @JsonProperty("comment")
  private String comment;

  // Constructors and Getters/Setters
}

异常:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.OffsetDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2020-07-27T02:49:58.564Z')

date-time 用于应用程序代码,但不适用于 Junit 设置代码。

您需要使用 JavaTimeModule 来配置 ObjectMapper 来处理 Java DateTime API 使用 :

<dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version>2.9.10</version>
</dependency>

然后注册模块给你ObjectMapper

 ObjectMapper objectMapper = new ObjectMapper();
 objectMapper.registerModule(new JavaTimeModule());
 objectMapper.readValue(TestData.TEST_JSON, RequestDTO.class);