I'm unsuccessfully trying to use MockWebServer + Retrofit + Coroutines on my Android unit tests. During debugging, I found out that OkHttp is running on a different thread, which is why my test always fails.
This is my rule to set the test dispatcher:
class MainCoroutineRule(
private val scheduler: TestCoroutineScheduler = TestCoroutineScheduler(),
val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(scheduler)
) : TestWatcher() {
val testScope = TestScope(testDispatcher)
override fun starting(description: Description) {
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description) {
super.finished(description)
Dispatchers.resetMain()
}
}
this is my ViewModel:
@HiltViewModel
class TestViewModel @Inject constructor(
private val repository: TestRepository,
@MainDispatcher private val dispatcher: CoroutineDispatcher
) : ViewModel() {
val hasData = MutableLiveData(false)
fun fetchSomething() {
viewModelScope.launch(dispatcher) {
when (repository.getSomething()) {
is Success -> {
hasData.value = true
}
else -> {
hasData.value = false
}
}
}
}
}
And finally the test:
class TestViewModelTest : MockServerSuite() {
@get:Rule
val taskExecutorRule = InstantTaskExecutorRule()
@get:Rule
val mainTestRule = MainCoroutineRule()
@Test
fun `my test`() = mainTestRule.testScope.runTest {
// setting up MockWebServer
val viewModel = TestViewModel(
repository = TestRepository(
api = testApi(server),
),
dispatcher = mainTestRule.testDispatcher
)
viewModel.fetchSomething()
assertThat(viewModel.hasData.value).isTrue
}
}
Since Retrofit is main-safe, I have no idea how to make it run on my testDispatcher. Am I missing something?
As Petrus mentioned, I already use getOrAwaitValue
, which works for simple scenarios.
Our requests fire other requests after receiving some data in most of our use cases.
Usually, I receive intermediate values of getOrAwaitValue and not the final LiveData I was expecting.