简体   繁体   English

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

[英]Unit test ViewModel with MeditorLiveData and coroutines

I created Unit test for my viewModel. 我为viewModel创建了单元测试。 This ViewModel just call loadAllStructures when created and call loadSubmissionBy when currentFilter or query changes (throught mediator) 此ViewModel在创建时仅调用loadAllStructures,在currentFilter或查询发生更改时调用loadSubmissionBy(通过中介)

But when I instanciate my ViewModel in before(), the test crash with this a nullPointerException at "addsource(query)" 但是当我在before()中实例化ViewModel时,测试在“ addsource(query)”处使用nullPointerException崩溃

If I put this line in comment, I got the same error but at "submissionRepository.loadSubmissionBy(...)" 如果我在注释中添加此行,则会出现相同的错误,但在“ submissionRepository.loadSubmissionBy(...)”处

"currentFilter" and "query" can be null and this case is handled by repo/dao by @Query (I'm using room) “ currentFilter”和“ query”可以为null,这种情况由@Query由repo / dao处理(我正在使用room)

What am I missing ? 我想念什么?

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 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)

The empty test should pass and the init of ViewModel should work like it's work in production 空测试应该通过并且ViewModel的init应该像在生产中一样工作

I will explain in currentFilter 我会在currentFilter解释

private val currentFilter: LiveData<SubmissionFilter> = structureFilterRepository.selectedFilter

.

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

your structureFilterRepository is mocked , it means all fields inside are null and all functions will return null 您的structureFilterRepository是模拟的,这意味着其中的所有字段均为null并且所有函数都将返回null

how to solve it 如何解决

     @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() }

        }

all functions or properties inside mocked objects which are used inside parentViewModelTest s properties , init block and constructor must be defined before this line 内的所有功能或性质mocked其内部使用的对象parentViewModelTest小号propertiesinit块和constructor必须在该行之前被定义

parentViewModelTest = SubmissionParentViewModel(structureRepository, structureFilterRepository, submissionRepository)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM