Step #8: Adding a Test Function
Now, we can start testing SingleModelMotor.
Add this test function to SingleModelMotorTest:
@Test
fun `initial state`() {
mainDispatcherRule.dispatcher.runCurrent()
runBlocking {
val item = underTest.states.first().item
assertEquals(testModel, item)
}
}
Here, we start by calling mainDispatcherRule.dispatcher.runCurrent() to get our TestCoroutineDispatcher from the MainDispatcherRule and tell that dispatcher to run any coroutines that are set up for that dispatcher. Our viewmodel functions are setting up coroutines to run on Dispatchers.Main, and Dispatchers.Main is tied to our TestCoroutineDispatcher through our MainDispatcherRule. The effect is that when we call runCurrent(), we cause those coroutines to be executed, making their requests of our (mock) repository. runCurrent() shows up with warning highlights, as it too is experimental, as with much of the test coroutines API that we are calling in MainDispatcherRule.
After that, we:
- Use
runBlocking()to say that we want to execute a block of code synchronously even though it uses asuspendfunction (first()) - In that block, call
first()on ourStateFlowto get the view-state - Use JUnit’s
assertEquals()function to confirm that the item from the view-state is our testToDoModelinstance
If you run this test function, it should succeed.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.