Kotest Test Clock Extension

This page explains the Test Clock extension.

Latest Release

The JVM provides the java.time.Clock interface, which is used to create instances. If you have code that depends on time, you can use Clock to generate values instead of using things like Instant.now() or System.currentTimeMillis().

Then, in tests, you can provide a fixed or controllable clock to avoid the problem where time changes every time the test runs. In production code, you can provide an instance such as Clock.systemUTC().

To use it, create an instance of TestClock by passing an instant and a zone offset.

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

You can control the clock with plus and minus, which accept durations, as follows.

clock.plus(6.minutes)

Note that the clock is mutable, and using plus or minus changes its internal state.


References