[英]How do I collage booking date inputs and return as LocalDate format., and validate year/month/day values with a boolean?
[英]How can I validate the format of LocalDate in test?
我在下面的 model class 中有cDate
,並且想編寫一個測試來驗證格式是否符合指定。 測試如下(為簡潔起見,我省略了一些),但它失敗並出現異常(如下)。 最初這是一個String
類型,它很好,因為我可以使用@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
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)
相關答案: 這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.