首页 > 解决方案 > 如何在测试中验证 LocalDate 的格式?

问题描述

cDate在下面的模型类中有,并且想编写一个测试来验证格式是否符合指定。测试如下(为简洁起见,我省略了一些),但它失败并出现异常(如下)。最初这是一种String很好的类型,因为我可以使用 a@Pattern(regexp = "")但要求是使用LocalDate. 当我在测试中使用正确的格式时,它会在与@JsonFormat模式进行比较时正确通过。那么如何验证LocalDate类型的格式呢?我还尝试添加throws DateTimeParseException到测试中并尝试在模式中使用 / 。

  @NotNull(message = "cDate is mandatory")
  @JsonFormat(pattern = "yyyy-MM-dd")
  @JsonDeserialize(using = LocalDateDeserializer.class)
  @JsonSerialize(using = LocalDateSerializer.class)
  private LocalDate cDate;

@Test
public void shouldValidateDateFormatFailure() {
  // Given
  String test = LocalDate.now().format(DateTimeFormatter.ofPattern("yy-MM-dd"));
  LocalDate date = LocalDate.parse(test);
....

java.time.format.DateTimeParseException: Text '20-06-04' could not be parsed at index 0

标签: javaspring-bootjunit5

解决方案


LocalDate 是 Java 8 时间包的一部分。您的依赖项中需要 jackson-modules-java8 或 jackson-datatype-jsr310 并将其注册到您的 Jackson ObjectMapper。

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)

相关答案:这里


推荐阅读