initMocksBeforeTest: How to configure suspending function?
Closed this issue · 1 comments
rs-georg commented
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
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()
}
}