streetsofboston
01/30/2019, 3:45 PMclass LogicTest {
private lateinit var viewmodel: ViewModel
private var repo: IRepository = mockk(relaxed = true)
@BeforeEach
fun setUp() {
viewmodel = ViewModel(repo, Dispatchers.Unconfined)
}
@Test
fun `when ViewModel init called then it calls repo init`() {
viewmodel.init()
verify { repo.init() }
}
@Test
fun `when ViewModel getName called then it calls repo getName`() {
viewmodel.getName { }
runBlocking {
coVerify { repo.getName() }
}
}
}
Note that I used MockK for the testing framework, not Mockito, but that should not matter.
Update: Using Dispatchers.Unconfined is good enough for these tests.
There is a known issues with Mockito verifying coroutines, but that should have been fixed in the latest version.ansman
01/30/2019, 3:46 PMstreetsofboston
01/30/2019, 3:47 PMlaunch
to runBlocking
ansman
01/30/2019, 3:49 PMstreetsofboston
01/30/2019, 3:50 PMsuspend
funs being called, TestCoroutineContext
is not necessary.
@ansman you are correct. The use of TestCoroutineContext
this way works well with code that is inherits the CoroutineScope with that context.