Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediatorLiveData doesn't work in JUnit tests?

So I've tried using MediatorLiveData for the rather simple use-case of converting an ISO country code (e.g. "US") to a country calling code (e.g. "+1") through the use of libphonenumber. The resulting screen works fine, but seems to fail JUnit tests, even when InstantTaskExecutorRule is used.

Example minimal unit test (in Kotlin) that I believe should pass, but fails instead:

import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.lifecycle.MediatorLiveData
import android.arch.lifecycle.MutableLiveData
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test

class MediatorLiveData_metaTest {
    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    @Test
    fun mediatorLiveData_metaTest() {
        val sourceInt = MutableLiveData<Int>()
        val mediatedStr = MediatorLiveData<String>()

        mediatedStr.addSource(sourceInt) {
            mediatedStr.value = it.toString()
        }

        sourceInt.value = 123

        assertEquals("123", mediatedStr.value) // says mediatedStr.value is null
    }
}
like image 890
Spheniscine Avatar asked Dec 24 '18 07:12

Spheniscine


1 Answers

Thanks to Reddit user matejdro; the answer was that like Schrödinger's proverbial cat, MediatorLiveData won't update itself unless observed, so I'd need a mediatedStr.observeForever{} to force it to update itself.

like image 73
Spheniscine Avatar answered Oct 06 '22 23:10

Spheniscine