【问题标题】:How to set the ZonedDateTime object to return a fixed time value while testing in Scala?在 Scala 中进行测试时,如何设置 ZonedDateTime 对象以返回固定时间值?
【发布时间】:2017-05-12 20:31:28
【问题描述】:

我正在使用 Scala WordSpec 编写单元测试用例。在测试返回当前时间的方法时,我想返回一个固定的时间。

我想在我的代码中模拟 ZonedDateTime.now().getHour 方法以返回一个固定值用于测试。

我尝试了下面的代码,但没有给出任何结果

 val mockZone = mock[ZonedDateTime]
    (mockZone.now("IN":"Asia/Kolkata").getHour)
      .expects()
      .returns(2)

【问题讨论】:

    标签: scala unit-testing scalatest


    【解决方案1】:

    您可以尝试以下方法获取time

    new SimpleDateFormat("HH:mm:ss").format(java.util.Date.from(ZonedDateTime.now(ZoneId.of("Asia/Kolkata")).toInstant))
    

    并关注以获取date

    new SimpleDateFormat("yyyy-MM-dd").format(java.util.Date.from(ZonedDateTime.now(ZoneId.of("Asia/Kolkata")).toInstant))
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 1970-01-01
      • 2011-10-01
      • 2016-08-22
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      相关资源
      最近更新 更多