java - 如何在测试中验证 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
解决方案
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)
相关答案:这里
推荐阅读
- java - org.osate.xtext.aadl2.Activator 找不到 org.osate.xtext.aadl2_1.0.0.qualifier 发生错误
- sql-server - 如何在 vb.net 中破坏 SQL 命令
- javascript - 是否可以公开这些功能进行测试?
- .net-core - 如何从命令行重置目标运行时
- node.js - 节点“加密”SHA256 哈希模型行为异常
- java - 在 Spring Boot 中对接口使用 @Autowired 注释
- javascript - 从其他 php 文件访问 java 脚本变量
- elasticsearch - 弹性搜索如何创建实时搜索
- php - 如何根据 laravel 上博客文章的 user_id 显示用户的照片?
- python-3.x - 在列表中追加时出现运行时错误