Kotest Current Instant Listeners Extension
This page introduces the Current Instant Listeners extension.
TIP
Since Kotest 5.6.0, current instant listeners are in the `io.kotest:kotest-extensions-now:${kotest-version}` artifact.
To use the features mentioned below, add it as a dependency.
Current Instant Listeners
For various reasons, such as setting the creation date of an entity, you may need to use the now static function from the java.time classes.
data class MyEntity(
creationDate: LocalDateTime = LocalDateTime.now()
)
But what should you do when you want to test that value? Every time now is called, the value changes.
For this, Kotest provides ConstantNowListener and the withConstantNow function.
While the code runs, the value you want to test will always be now.
val foreverNow = LocalDateTime.now()
withConstantNow(foreverNow) {
LocalDateTime.now() shouldBe foreverNow
delay(10) // Code is taking a small amount of time to execute, but `now` changed!
LocalDateTime.now() shouldBe foreverNow
}
Or you can use a listener for all tests:
override fun listeners() = listOf(
ConstantNowTestListener(foreverNow)
)
CAUTION
`withContantNow` and `ConstantNowTestListener` are very sensitive to race conditions. When you use them, you mock the static `now` method globally for the entire JVM instance, so results may be inconsistent if tests run in parallel.