Kotest Current Instant Listeners Extension

This page introduces the Current Instant Listeners extension.

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)
)

References