setValue and postValue on MutableLiveData in UnitTest

15.6k views Asked by At

I try to test some methods on my Application but I get an error when calling mutablelivedata.postValue. Here is a snippet and the error message:

@Test
public void callStartScreenRepository(){
    Observer<User> userObserver = mock(Observer.class);
    startScreenViewModel.returnUser().observeForever(userObserver);
    maennlich = new User();
    maennlich.setVorname("Christian");
    MutableLiveData<User> userTest = new MutableLiveData<>();
    userTest.postValue(maennlich);
    when(startScreenRepository.userWebService("testUser")).thenReturn(userTest);
    verify(userObserver).onChanged(maennlich);
}

java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.

at android.os.Looper.getMainLooper(Looper.java)
at android.arch.core.executor.DefaultTaskExecutor.postToMainThread(DefaultTaskExecutor.java:48)
at android.arch.core.executor.AppToolkitTaskExecutor.postToMainThread(AppToolkitTaskExecutor.java:100)
at android.arch.lifecycle.LiveData.postValue(LiveData.java:277)
at android.arch.lifecycle.MutableLiveData.postValue(MutableLiveData.java:28)
at com.example.cfrindt.foodtracking.ViewModels.StartScreenViewModelTest.callStartScreenRepository(StartScreenViewModelTest.java:102)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

I receive this error no matter if I am using setValue() or postValue(). How can I make it work?

4

There are 4 answers

4
Carlos Daniel On BEST ANSWER

First thing is that you need to work with the InstantTaskExecutorRule, that means:

@Rule public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule();

This will allow to work with MutableLiveData instantly. Remember to include in your app's build.gradle the import:

testCompile "android.arch.core:core-testing:$rootProject.ext.arch_version"

Then, you need to either define a JUnit Rule with a rule overriding RxSchedulers or within the @Before override the Schedulers as well using RxAndroidPlugins (if you are using RxJava)

RxSchedulersOverrideRule:

public class RxSchedulersOverrideRule implements TestRule {
    @Override public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override public void evaluate() throws Throwable {
            RxAndroidPlugins.reset();
            RxAndroidPlugins.setMainThreadSchedulerHandler(scheduler -> Schedulers.trampoline());

        RxJavaPlugins.reset();
        RxJavaPlugins.setIoSchedulerHandler(scheduler -> Schedulers.trampoline());
        RxJavaPlugins.setComputationSchedulerHandler(scheduler -> Schedulers.trampoline());
        RxJavaPlugins.setNewThreadSchedulerHandler(scheduler -> Schedulers.trampoline());

        base.evaluate();

        RxAndroidPlugins.reset();
        RxJavaPlugins.reset();
      }
    };
  }
}

And calling it in the test class:

@Rule public RxSchedulersOverrideRule rxSchedulersOverrideRule = new RxSchedulersOverrideRule();

The other option is calling within setup() in @Before:

RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerCallable -> Schedulers.trampoline());

After using this you need to reset in @After's tearDownClass():

RxAndroidPlugins.reset(); 
0
YoSoy On

In case none of the solutions worked alike in my case, if you are using a later version of Gradle and you are using androix, make sure you import from androix in your build gradle.

  implementation 'androidx.arch.core:core-testing:$version' 

instead of

 implementation 'android.arch.core:core-testing:$version'
1
AdamHurwitz On

Ensure Observer Is Not On The Main Thread

Jeroen Mols outlines each implementation for JUnit 4 and JUnit 5. I used the Junit 5 approach for Coinverse Open App's local unit tests using Kotlin, JUnit 5, MockK, and AssertJ libraries.

JUnit 4

@Carlos Daniel's solution to implement the InstantExecutorRule is correct for JUnit 4.

ExampleUnitTest.kt

class ExampleUnitTest {

    @get:Rule
    val rule = InstantTaskExecutorRule()

    @Test
    fun `my test`() {
        val mutableLiveData = MutableLiveData<String>()
        mutableLiveData.postValue("test")
        assertEquals("test", mutableLiveData.value)
    }
}

build.gradle

dependencies {
    testImplementation 'android.arch.core:core-testing:X.X.X'
}

JUnit 5

InstantExecutorExtension.kt

import androidx.arch.core.executor.ArchTaskExecutor
import androidx.arch.core.executor.TaskExecutor
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext

class InstantExecutorExtension : BeforeEachCallback, AfterEachCallback {
    override fun beforeEach(context: ExtensionContext?) {
        ArchTaskExecutor.getInstance().setDelegate(object : TaskExecutor() {
            override fun executeOnDiskIO(runnable: Runnable) = runnable.run()
            override fun postToMainThread(runnable: Runnable) = runnable.run()
            override fun isMainThread(): Boolean = true
        })
    }

    override fun afterEach(context: ExtensionContext?) {
        ArchTaskExecutor.getInstance().setDelegate(null)
    }
}

The InstantExecutorExtension is implemented with an annotation in the local unit test class.

ContentViewModelTest.kt

...
import androidx.paging.PagedList
import com.google.firebase.Timestamp
import io.mockk.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith

@ExtendWith(InstantExecutorExtension::class)
class ContentViewModelTest {
    val timestamp = getTimeframe(DAY)

    @BeforeAll
    fun beforeAll() {
        mockkObject(ContentRepository)
    }

    @BeforeEach
    fun beforeEach() {
        clearAllMocks()
    }

    @AfterAll
    fun afterAll() {
        unmockkAll()
    }

    @Test
    fun `Feed Load`() {
        val content = Content("85", 0.0, Enums.ContentType.NONE, Timestamp.now(), "",
            "", "", "", "", "", "", MAIN,
            0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0, 0.0)
        every {
            getMainFeedList(any(), any())
        } returns MutableLiveData<Lce<ContentResult.PagedListResult>>().also { lce ->
            lce.value = Lce.Content(
                ContentResult.PagedListResult(
                    pagedList = MutableLiveData<PagedList<Content>>().apply {
                        this.value = listOf(content).asPagedList(
                            PagedList.Config.Builder().setEnablePlaceholders(false)
                                .setPrefetchDistance(24)
                                .setPageSize(12)
                                .build())
                        }, errorMessage = ""))
        }
        val contentViewModel = ContentViewModel(ContentRepository)
        contentViewModel.processEvent(ContentViewEvent.FeedLoad(MAIN, DAY, timestamp, false))
        assertThat(contentViewModel.feedViewState.getOrAwaitValue().contentList.getOrAwaitValue()[0])
            .isEqualTo(content)
        assertThat(contentViewModel.feedViewState.getOrAwaitValue().toolbar).isEqualTo(
            ToolbarState(
                    visibility = GONE,
                    titleRes = app_name,
                    isSupportActionBarEnabled = false))
        verify {
            getMainFeedList(any(), any())
        }
        confirmVerified(ContentRepository)
    }
}
0
Rainmaker On

@Carlos Daniel's answer helped me a lot but faced another issue that the Rule wasn't applied with PowerMockRunner. For those having the same problem, here is the solution:

@RunWith(PowerMockRunner::class)
@PowerMockRunnerDelegate(MockitoJUnitRunner::class) //this line allows you to use the powermock runner and mockito runner
@PrepareForTest(UnderTestClass::class)
class UnderTestClassTest {
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()