kosi-libs / MocKMP

A mocking processor for Kotlin Multiplatform
https://kosi-libs.org/mockmp
MIT License
183 stars 12 forks source link

initMocksBeforeTest: How to configure suspending function? #67

Closed rs-georg closed 10 months ago

rs-georg commented 10 months ago

I need to configure a suspending function of a mock before executing each test. However, this is obviously not possible since initMocksBeforeTest() is not suspending. Is there a good way to achieve this anyway?

override fun initMocksBeforeTest() {
  everySuspending { myMock.setState(isAny()) } returns someData
}
rs-georg commented 10 months ago

I've found a solution. If anyone has the same issue or needs to setup suspending functions, this is how I did it

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.kodein.mock.Mock
import org.kodein.mock.tests.TestsWithMocks
import kotlin.test.Test

@OptIn(ExperimentalCoroutinesApi::class)
class MyTest : TestsWithMocks() {
    override fun setUpMocks() = injectMocks(mocker)

    @Mock
    internal lateinit var mockMyClassWithSuspend: MyClassWithSuspend

    private val dispatcher = UnconfinedTestDispatcher()

    override fun initMocksBeforeTest() {
        runBlocking(dispatcher) {
            everySuspending { mockMyClassWithSuspend.sayHello() } returns "Hello, World!"
        }
    }

    @Test
    fun `when this_given that_then something`() = runTest(dispatcher) {
      TODO()
    }
}