Rogen George
Rogen George

Reputation: 465

How to set the ZonedDateTime object to return a fixed time value while testing in Scala?

I'm using Scala WordSpec for writing unit test cases. While testing a method which returns the current time, I want to return a fixed time.

I want to mock ZonedDateTime.now().getHour method in my Code to return a fixed value for the purpose of testing.

I tried the code below but its not giving any results

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

Upvotes: 0

Views: 489

Answers (1)

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

You can try the following to get the time

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

and following to get the date

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

Hope it helps

Upvotes: 1

Related Questions