TestTimeSource

A time source that has programmatically updatable readings. It is useful as a predictable source of time in tests.

The current reading value can be advanced by the specified duration amount with the operator plusAssign:

val timeSource = TestTimeSource()
timeSource += 10.seconds

Time marks returned by this time source can be compared for difference with other time marks obtained from the same time source.

Implementation note: the current reading value is stored as a Long number of nanoseconds, thus it's capable to represent a time range of approximately ±292 years. Should the reading value overflow as the result of plusAssign operation, an IllegalStateException is thrown.

Since Kotlin

1.9

Samples

import kotlin.test.Test
import kotlin.time.Duration.Companion.seconds
import kotlin.time.*

fun main() { 
   //sampleStart 
   val testSource = TestTimeSource()
val elapsed = testSource.measureTime {
    println("Pretending this function executes 10 seconds")
    testSource += 10.seconds
}
println("Time elapsed: ${elapsed.inWholeMilliseconds} milliseconds ($elapsed)") 
   //sampleEnd
}
import kotlin.test.Test
import kotlin.time.Duration.Companion.seconds
import kotlin.time.*

fun main() { 
   //sampleStart 
   val testSource = TestTimeSource()
val result = testSource.measureTimedValue {
    println("Pretending this function executes 10 seconds")
    testSource += 10.seconds
    42
}
println("Computed result: ${result.value}, time elapsed: ${result.duration}") 
   //sampleEnd
}

Constructors

Link copied to clipboard
constructor()

Properties

Link copied to clipboard
protected val unit: DurationUnit

The unit in which this time source's readings are expressed.

Since Kotlin 1.9

Functions

Link copied to clipboard
open override fun markNow(): ComparableTimeMark

Marks a point in time on this time source.

Since Kotlin 1.9
Link copied to clipboard
inline fun TimeSource.measureTime(block: () -> Unit): Duration

Executes the given function block and returns the duration of the elapsed time interval.

Since Kotlin 1.9
Link copied to clipboard
inline fun <T> TimeSource.measureTimedValue(block: () -> T): TimedValue<T>

Executes the given function block and returns an instance of TimedValue class, containing both the result of function execution and the duration of the elapsed time interval.

Since Kotlin 1.9
Link copied to clipboard
operator fun plusAssign(duration: Duration)

Advances the current reading value of this time source by the specified duration.

Since Kotlin 1.9
Link copied to clipboard
protected open override fun read(): Long

This protected method should be overridden to return the current reading of the time source expressed as a Long number in the unit specified by the unit property.

Since Kotlin 1.9