简体   繁体   English

如何在测试中验证 LocalDate 的格式?

[英]How can I validate the format of LocalDate in test?

I have the cDate in my model class below, and want to write a test to validate the format is as specified.我在下面的 model class 中有cDate ,并且想编写一个测试来验证格式是否符合指定。 The test is below (I have omitted some for brevity), but it fails with an exception (below).测试如下(为简洁起见,我省略了一些),但它失败并出现异常(如下)。 Originally this was a String type which was fine as I can use a @Pattern(regexp = "") but the requirement is to use LocalDate .最初这是一个String类型,它很好,因为我可以使用@Pattern(regexp = "")但要求是使用LocalDate When I use the correct format in the test, it correctly passes as it is being compared to the @JsonFormat pattern.当我在测试中使用正确的格式时,它在与@JsonFormat模式进行比较时正确通过。 So how can I validate the format of LocalDate type?那么如何验证LocalDate类型的格式呢? I have also tried adding throws DateTimeParseException to the test and tried using / in the pattern.我还尝试将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

LocalDate is part of the Java 8 time packages. LocalDate 是 Java 8 时间包的一部分。 You need jackson-modules-java8 or jackson-datatype-jsr310 in your dependencies and register it to your Jackson ObjectMapper.您的依赖项中需要 jackson-modules-java8 或 jackson-datatype-jsr310 并将其注册到 Jackson ObjectMapper。

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

Related answer: here相关答案: 这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM