Hello, i'm trying to mock Instant but I can't seem to get it to work. My approach:
object 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?