tim
10/11/2020, 8:47 PMobject MockkInstant {
var value: Instant = Instant.now()
fun mock() {
mockkStatic(Instant::class)
every {
Instant.now()
} answers {
value.minusMillis(0) // line 22 from stack trace below
}
}
fun clear() {
clearStaticMockk(Instant::class)
}
fun step(duration: Duration = 1.seconds) {
value = value.add(duration) // extension function defined elsewhere
}
}
Now in my tests i'm trying to do this:
"fixes calls to Instant.now()" {
val a = Instant.now()
delay(1)
val b = Instant.now()
a.shouldBe(b)
}
But I'm getting an error from the answers
block:
Empty list doesn't contain element at index 0.
java.lang.IndexOutOfBoundsException: Empty list doesn't contain element at index 0.
at kotlin.collections.EmptyList.get(Collections.kt:35)
at kotlin.collections.EmptyList.get(Collections.kt:23)
at io.mockk.MockKAnswerScope.getValueAny(API.kt:3834)
at io.mockk.MockKAnswerScope.getValue(API.kt:2188)
at io.glimpseprotocol.testing.mockk.MockkInstant$mock$2.invoke(MockkInstant.kt:22)
at io.glimpseprotocol.testing.mockk.MockkInstant$mock$2.invoke(MockkInstant.kt:13)
at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2092)
at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2069)
at io.mockk.FunctionAnswer.answer(Answers.kt:19)
...
I've seen other people using returns, but afaik that returns the same Instant object whereas I want to create a new one each time Instant.now() is called. Any suggestions?LeoColman
10/11/2020, 10:05 PMtim
10/12/2020, 7:13 AMLeoColman
10/12/2020, 7:35 AMtim
10/12/2020, 8:06 AMreturns
rather than answers
@OptIn(ExperimentalTime::class)
object MockkInstant {
var step: Duration = 0.seconds
private lateinit var base: Instant
fun mock(from: Instant = Instant.now()) {
base = from
mockkStatic(Instant::class)
every {
Instant.now()
} answers {
base.add(step)
}
}
fun clear() {
clearStaticMockk(Instant::class)
}
fun step(duration: Duration = 1.seconds) {
step += duration
}
}