3

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.

Ygor
  • 188
  • 8

1 Answers1

1

Try to use getOrAwaitValue :)

class TestViewModelTest {
    @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.getOrAwaitValue()).isTrue
    }
}

@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun <T> LiveData<T>.getOrAwaitValue(
    time: Long = 2,
    timeUnit: TimeUnit = TimeUnit.SECONDS,
    afterObserve: () -> Unit = {}
): T {
    var data: T? = null
    val latch = CountDownLatch(1)
    val observer = object : Observer<T> {
        override fun onChanged(o: T?) {
            data = o
            latch.countDown()
            this@getOrAwaitValue.removeObserver(this)
        }
    }
    this.observeForever(observer)

    try {
        afterObserve.invoke()

        // Don't wait indefinitely if the LiveData is not set.
        if (!latch.await(time, timeUnit)) {
            throw TimeoutException("LiveData value was never set.")
        }

    } finally {
        this.removeObserver(observer)
    }

    @Suppress("UNCHECKED_CAST")
    return data as T
}
  • Thanks, Petrus! I'm already using it, and it works perfectly for some scenarios. I come up with a straightforward example. Our requests fire other requests after receiving some data in most of our use cases. Usually, I end up receiving intermediate values of `getOrAwaitValue` – Ygor Mar 16 '22 at 12:51