Recca Chao
09/29/2021, 2:16 PMEmil Kantis
09/29/2021, 2:18 PMRecca Chao
09/29/2021, 2:23 PMQuincy
09/29/2021, 2:32 PMjava.time.Clock
, if you are on the JVM.Emil Kantis
09/29/2021, 2:47 PMobject Time { fun now() = Instant.now() }
, for instance, and you can easily do mockkObject(Time)
every { Time.now() } returns myTimestamp
Recca Chao
09/29/2021, 2:56 PMQuincy
09/29/2021, 3:05 PMRecca Chao
09/29/2021, 4:11 PMval fixedClock = Clock.fixed(
Instant.parse("2022-01-01T23:59:59Z"),
ZoneId.of("UTC")
)
mockkStatic(Clock::class)
every { Clock.systemUTC() } returns fixedClock
Assert.assertThat(isValidDate(), `is`(false))
Quincy
09/29/2021, 4:13 PMclass Sut(private val clock: Clock) {
fun doSomething(): OffsetDateTime {
return OffsetDateTime.now(clock)
}
}
fun `my_test`() {
val now = Instant.of(1L)
val clock = Clock.fixed(now)
assertThat(
Sut(clock).doSomething(),
equalTo(OffsetDateTime.of(...))
)
}
Recca Chao
09/29/2021, 4:22 PMQuincy
09/29/2021, 4:50 PMthanksforallthefish
09/30/2021, 6:00 AMwithConstantNow(Instant.now())
. behind the scene it uses mockkStatic
so it only works when in your code you do val date = Instant.now()
and it won’t with val date = LocalDate.now()
.
you can also do withConstantNow(LocalDate.now())
or every other time-setting instruction, though personally I still prefer to use a clock. not a big fan of static mocking in general (as much as I would actually remove it from the library)