Skip to main content
Version: 5.6

Test Clock

Latest Release

The JVM provides the java.time.Clock interface which is used to generate Instants. When we have code that relies on time, we can use a Clock to generate the values, rather than using things like Instant.now() or System.currentTimeMillis().

Then in tests we can provide a fixed or controllable clock which avoids issues where the time changes on each test run. In your real code, you provide an instance of Clock.systemUTC() or whatever.

note

The following module is needed: io.kotest.extensions:kotest-extensions-clock in your build. Search maven central for latest version here.

In order to use it, we create an instance of the TestClock passing in an instant and a zone offset.

val timestamp = Instant.ofEpochMilli(1234)
val clock = TestClock(timestamp, ZoneOffset.UTC)

We can control the clock via plus and minus which accept durations, eg

clock.plus(6.minutes)

Note that the clock is mutable, and the internal state is changed when you use plus or minus.