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.9Samples
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
}
Properties
Functions
Marks a point in time on this time source.
Executes the given function block and returns the duration of the elapsed time interval.
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.
Advances the current reading value of this time source by the specified duration.