Spring Boot存储库测试中的日期格式

问题描述 投票:-1回答:2

我正在使用以下代码对存储库功能进行集成测试。但是,由于日期太早而失败。 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);
java spring-boot integration-testing simpledateformat assertj
2个回答
0
投票

您正在做的是解析(从字符串到日期),您需要格式化(从日期到字符串)。

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);

这里readFormatwriteFormat相同,但可以不同。


0
投票

在我看来,TestBean被声明为持有java.util.Date,但是从TestBean返回的findById()实例却持有java.sql.Timestamp。非常不幸(如果是真的)。​​

Timestamp被实现为Date的子类。这两个类的设计都差强人意,并且已经过时,我们不应该再使用它们了。尽管存在子类关系,但根据文档,我们不应将Timestamp视为Date的一种。将Timestamp实现为Date的子类是真正的技巧。将Timestamp放入对象的Date字段中是错误的。我也不认为我们有意在模型bean中使用Timestamp。它仅用于与数据类型为timestamptimestamp 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。

链接

© www.soinside.com 2019 - 2024. All rights reserved.