0

I have the cDate in my model class below, and want to write a test to validate the format is as specified. 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. When I use the correct format in the test, it correctly passes as it is being compared to the @JsonFormat pattern. So how can I validate the format of LocalDate type? I have also tried adding throws DateTimeParseException to the test and tried using / in the pattern.

  @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
Coder
  • 197
  • 1
  • 17
  • you are adding test for LocalDateSerializer, right? – Nagaraddi Jun 04 '20 at 10:35
  • LocalDate.parse(test) uses default ISO date formatter. you can use LocalDate.parse(test, DateTimeFormatter.ofPattern("yy-MM-dd")) to parse it. – Nagaraddi Jun 04 '20 at 10:38
  • I used LocalDate date = LocalDate.parse(test, DateTimeFormatter.ofPattern("yy-MM-dd")); but it passes, it should fail as its not matching whats defined in @JsonFormat – Coder Jun 04 '20 at 10:43
  • You can use javax-validation-api, It will help you to pass some invalid values. And try to use String instead of `localdate` – Ibrahim AlTamimi Jun 04 '20 at 11:22

1 Answers1

1

LocalDate is part of the Java 8 time packages. You need jackson-modules-java8 or jackson-datatype-jsr310 in your dependencies and register it to your Jackson ObjectMapper.

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

Related answer : here

boredDev
  • 317
  • 3
  • 18