commonMain.io.mockk.impl.stub.AnswerAnsweringOpportunity.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mockk-jvm Show documentation
Show all versions of mockk-jvm Show documentation
Mocking library for Kotlin
package io.mockk.impl.stub
import io.mockk.*
import io.mockk.impl.InternalPlatform
class AnswerAnsweringOpportunity(
private val matcherStr: () -> String
) : MockKGateway.AnswerOpportunity, Answer {
private var storedAnswer: Answer? = null
private val firstAnswerHandlers = mutableListOf<(Answer) -> Unit>()
private fun getAnswer() = storedAnswer ?: throw MockKException("no answer provided for ${matcherStr()}")
override fun answer(call: Call) = getAnswer().answer(call)
override suspend fun coAnswer(call: Call) = getAnswer().answer(call)
override fun provideAnswer(answer: Answer) {
InternalPlatform.synchronized(this) {
val currentAnswer = this.storedAnswer
this.storedAnswer = if (currentAnswer == null) {
notifyFirstAnswerHandlers(answer)
answer
} else {
ManyAnswersAnswer(listOf(currentAnswer, answer))
}
}
}
private fun notifyFirstAnswerHandlers(answer: Answer) {
firstAnswerHandlers.forEach { it(answer) }
}
fun onFirstAnswer(handler: (Answer) -> Unit) {
InternalPlatform.synchronized(this) {
firstAnswerHandlers.add(handler)
}
}
}