使用MeditorLiveData和协程进行单元测试ViewModel

时间:2019-08-09 15:47:19

标签: android unit-testing kotlin mvvm android-livedata

我为viewModel创建了单元测试。此ViewModel在创建时仅调用loadAllStructures,在currentFilter或查询发生更改时(通过中介)调用loadSubmissionBy

但是当我在before()中实例化ViewModel时,测试在“ addsource(query)”处出现nullPointerException崩溃

如果我在注释中添加此行,则会出现相同的错误,但是在“ submissionRepository.loadSubmissionBy(...)”处

“ currentFilter”和“ query”可以为null,这种情况是通过@Query(我正在使用房间)由repo / dao处理的。

我想念什么?

ViewModel

private val currentFilter: LiveData<SubmissionFilter> = structureFilterRepository.selectedFilter
var mQuery = MutableLiveData("")
private val query: LiveData<String> = mQuery

private val mediator = MediatorLiveData<List<Submission>>().apply {
        addSource(currentFilter) {
            populate()
            spyStructures()
        }
        addSource(query) { populate() }
    }
    val submissionModels: LiveData<List<Submission>>
        get() = mediator

fun init() {

    viewModelScope.launch {
        structures.value = structureRepository.loadAllStructures().map { it.structureId to it }.toMap()
    }

    populate()
}

private fun populate() {
    val result = submissionRepository.loadSubmissionBy(currentFilter.value, query.value?.trim())
    mediator.addSource(result) { mediator.value = it }
}

ViewModelTest

@ExperimentalCoroutinesApi
@RunWith(RobolectricTestRunner::class)
class SubmissionViewModelTest: KoinTest {
    @Mock
    private lateinit var structureRepository: StructureRepository
    @Mock
    private lateinit var structureFilterRepository: SubmissionFilterRepository
    @Mock
    private lateinit var submissionRepository: SubmissionRepository

    private val fakeStructures = createFakeStructure(5)


    @get:Rule
    val rule = InstantTaskExecutorRule()

     @Before
    fun before() {
        MockitoAnnotations.initMocks(this)

        parentViewModelTest = SubmissionParentViewModel(structureRepository, structureFilterRepository, submissionRepository)

        runBlocking { whenever(structureRepository.loadAllStructures()).thenReturn(fakeStructures) }

        runBlocking { parentViewModelTest.init() }

    }

    @Test
    fun empty() {

    }
}

Stacktrace

java.lang.NullPointerException
    at androidx.arch.core.internal.SafeIterableMap.get(SafeIterableMap.java:48)
    at androidx.arch.core.internal.SafeIterableMap.putIfAbsent(SafeIterableMap.java:66)
    at androidx.lifecycle.MediatorLiveData.addSource(MediatorLiveData.java:87)
    at com.daxium.air.base.submissions.SubmissionParentViewModel.<init>(SubmissionParentViewModel.kt:33)
    at com.daxium.air.app.submissions.SubmissionViewModelTest.before(SubmissionViewModelTest.kt:89)
    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.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:228)
    at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:110)
    at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:37)
    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.robolectric.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:64)
    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:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

空测试应该通过,并且ViewModel的初始化应该像在生产环境中一样工作

1 个答案:

答案 0 :(得分:0)

我将在currentFilter

中进行解释
private val currentFilter: LiveData<SubmissionFilter> = structureFilterRepository.selectedFilter

 addSource(currentFilter) {
                populate()
                spyStructures()
            }

您的structureFilterRepository被模拟,这意味着里面的所有字段都是null,并且所有函数都将返回null

解决方法

     @Before
        fun before() {
            MockitoAnnotations.initMocks(this)
//define what will return your mocked objects
            whenever(structureFilterRepository.selectedFilter).thenReturn(/*return what you need to use */)


            parentViewModelTest = SubmissionParentViewModel(structureRepository, structureFilterRepository, submissionRepository)

            runBlocking { whenever(structureRepository.loadAllStructures()).thenReturn(fakeStructures) }

            runBlocking { parentViewModelTest.init() }

        }

mocked的{​​{1}}的{​​{1}}块,parentViewModelTest块和properties中使用的init对象内部的所有函数或属性必须在此行之前定义

constructor