我正在使用以下代码对存储库功能进行集成测试。但是,由于日期太早而失败。 SimpleDateFormat的输出为“ Wed Jan 01 10:10:10 MST 2020”,但数据库中的日期为“ 2020-01-01 10:10:10.0”。他们有解决这个问题的简便方法吗?
Optional<TestBean> testBean = testBeanRepository.findById(1L);
TestBean toReturn = new TestBean();
toReturn.setAccountNumber(123456789);
toReturn.setId(1L);
toReturn.setCustomerName("Peter");
toReturn.setModifiedDate(new SimpleDateFormat("yyyy-mm-dd HH:mm:ss").parse("2020-01-01 10:10:10"));
assertThat(testBean)
.isPresent()
.hasValue(toReturn);
您正在做的是解析(从字符串到日期),您需要格式化(从日期到字符串)。
SimpleDateFormat readFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
SimpleDateFormat writeFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Optional<TestBean> testBean = testBeanRepository.findById(1L);
TestBean toReturn = new TestBean();
toReturn.setAccountNumber(123456789);
toReturn.setId(1L);
toReturn.setCustomerName("Peter");
toReturn.setModifiedDate(writeFormat.format(readFormat.parse("2020-01-01 10:10:10")));
assertThat(testBean)
.isPresent()
.hasValue(toReturn);
这里readFormat
和writeFormat
相同,但可以不同。
在我看来,TestBean
被声明为持有java.util.Date
,但是从TestBean
返回的findById()
实例却持有java.sql.Timestamp
。非常不幸(如果是真的)。
Timestamp
被实现为Date
的子类。这两个类的设计都差强人意,并且已经过时,我们不应该再使用它们了。尽管存在子类关系,但根据文档,我们不应将Timestamp
视为Date
的一种。将Timestamp
实现为Date
的子类是真正的技巧。将Timestamp
放入对象的Date
字段中是错误的。我也不认为我们有意在模型bean中使用Timestamp
。它仅用于与数据类型为timestamp
和timestamp with time zone
的SQL数据库列之间的数据传输。
因此,好的解决方案是:更改TestBean
类以容纳属于现代Java日期和时间API类java.time的现代日期时间对象。
如果无法更改在TestBean
类中声明的类型,则仍有几个可能的改进:
Date
,而不是Timestamp
。Instant
而不是Date
的getter和setter,以便您的类可以更好地使用java.time与代码进行互操作。新方法将进行必要的转换。然后使用新的设置器在toReturn
中设置值。如果您不能执行任何一项操作,而您又被迫成为黑客的一部分,那么当然可以通过以下方法将modifiedDate
设置为老式的Timestamp
。我建议:
toReturn.setModifiedDate(Timestamp.from(Instant.parse("2020-01-01T17:10:10Z")));
我给的时间是17:10:10。这次是以UTC表示(用Z
表示)。我假设您在问题中提到的MST是北美山区标准时间(不是马来西亚标准时间?),如果是,那么此时间对应于您所在时区中所需的10:10:10。
java.sql.Timestamp