https://kotlinlang.org logo
Title
s

streetsofboston

01/30/2019, 3:45 PM
@curioustechizen Try this
class 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.
a

ansman

01/30/2019, 3:46 PM
Doing this is not recommend since you’re not blocking until the context is complete in the tests
s

streetsofboston

01/30/2019, 3:47 PM
Typo, I changed
launch
to
runBlocking
a

ansman

01/30/2019, 3:49 PM
Still doesn’t really help since the view model’s context and `runBlocking`’s context are different. The propert solution is to wait until the view model’s context is complete (meaning all coroutines have completed)
s

streetsofboston

01/30/2019, 3:50 PM
Actually, for direct verification of
suspend
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.
Updated the sample.