All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.io.mockk.impl.stub.AnswerAnsweringOpportunity.kt Maven / Gradle / Ivy

There is a newer version: 1.13.12
Show newest version
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)
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy