Skip to content Skip to sidebar Skip to footer

Mutablelivedata Is Null In Junittest

I want to write a unit test. Therefore I need MutableLiveData. I started with a very basic test for setup but I cannot instantiate a MutableLiveData object. I is always null when I

Solution 1:

Looks like you are missing the android.arch.core:core-testing dependency.

testImplementation "android.arch.core:core-testing:1.1.1"

This allows you to use the InstantTaskExecutorRule in your test, which will get rid of the isMainThread call.

https://developer.android.com/reference/android/arch/core/executor/testing/InstantTaskExecutorRule.html

@RulepublicInstantTaskExecutorRuleinstantTaskExecutorRule=newInstantTaskExecutorRule();

Solution 2:

Add an executor InstantTaskExecutorRule() as a member of the Test class

A JUnit Test Rule that swaps the background executor used by the Architecture Components with a different one which executes each task synchronously. You can use this rule for your host side tests that use Architecture Components.

//@RunWith(JUnit4::class)   // For JUnit4@ExtendWith(InstantExecutorExtension::class)   // For JUnit5
class FilterViewModelTest {

    @Rule@JvmField
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    @Test
    fun test() {
        //Here you don't ask if isMainThread
    }
}

build.gradle(:mobile)

android {
    //...
    dependencies {
        //...
        testImplementation 'androidx.arch.core:core-testing:2.1.0'
        androidTestImplementation 'androidx.arch.core:core-testing:2.1.0'
    }
}

GL

InstantTaskExecutorRule

Solution 3:

I had this error and solved it by adding InstantTaskExecutorRule:

privatelateinitvar contactProfileViewModel: ContactProfileViewModel

privateval getStatusesForContact: GetStatusesForContact = mockk(relaxed = true)
privateval getStory: GetUserLastStory = mockk(relaxed = true)
privateval successStatusesCaptor = slot<((List<StatusDomain>) -> Unit)>()
privateval successStoryCaptor = slot<((List<StoryDomain>) -> Unit)>()

@get:Ruleval rule: TestRule = InstantTaskExecutorRule()

@BeforefunsetUp(){
    contactProfileViewModel = ContactProfileViewModel(getStatusesForContact, getStory)
}

Post a Comment for "Mutablelivedata Is Null In Junittest"