Lukasz Kalnik
01/25/2022, 1:07 PMclass Presenter(
val api: Api,
coroutineContext: CoroutineContext
) {
val coroutineScope = CoroutineScope(coroutineContext)
fun onAttachView(view View) {
coroutineScope.launch {
api.getDetail()
}
}
}
Test:
import io.mockk.*
class PresenterTest {
val testCoroutineScope = TestCoroutineScope()
val presenter = Presenter(
api = mockk(),
coroutineContext = testCoroutineScope.coroutineContext
)
val view = mockk()
@AfterEach
fun tearDown() {
testCoroutineScope.cleanupTestCoroutines()
}
@Test
fun `when view attached then call API`() {
presenter.test().attachView(view)
coVerify { api.getData() }
}
}
How do I migrate it to coroutine-test 1.6.0?Lukasz Kalnik
01/25/2022, 1:09 PMTestCoroutineScope()
with TestScope()
and then I can remove the whole tearDown()
function? Or do I need to also wrap each test into runTest {}
now?Lukasz Kalnik
01/25/2022, 1:10 PMrunTest {}
connected to TestScope()
? Does it automatically use the instance I created in my test class or do I need to pass my TestScope
instance to the runTest
method somehow?Lukasz Kalnik
01/25/2022, 3:11 PMval testScope = TestScope(UnconfinedTestDispatcher())
val testPresenter = Presenter(
coroutineContext = testScope.coroutineContext
)
}
@Test
fun `some test`() = testScope.runTest {
// test body
}
The UnconfinedTestDispatcher
is apparently important, as with StandardTestDispatcher
the coroutines you launch inside your presenter won't be executed (for whatever reason).