结合RxJava进行LiveData排放的单元测试

问题描述 投票:0回答:1

我一直在测试我们的业务逻辑的问题单元。问题是当我想对实时数据的所有排放进行单元测试时。现在,我只得到最后一个发出的值,但是我想对所有一个一个发出的值进行单元测试。

这是我的粗略设置。

[这是我的viewModelonSaveEventclick事件的外观

        disposable.add(finalSource
        .observeOn(schedulerProvider.ui())
            .doOnSubscribe {
                // show spinner
                _myLiveData.value = Loading(toShow = true, loadingMessage = "Loading")
            }
            .doAfterTerminate {
                // remove spinner
                _myLiveData.value = Loading(toShow = false)

            }
            .subscribe { resource ->
                // Update either on success or error.
                _myLiveData.value = resource
        }
    )

我的视图模型测试看起来像这样。

@Test
fun testOnSaveEvent() {
    // Other setup code.
    Mockito.`when`(myRepo.onSave()).thenReturn(mockSingle)
    myViewModel.onSaveEvent(salesTaxCompanyInfo)

    testScheduleProvider.ui().triggerActions()

    // I see that the value is of type Loading
    val firstValue = myViewModel.myLiveData.getOrAwaitValue()

    // The next value is also Loading, although I would like to see the success event.
    val secondValue = myViewModel.myLiveData.getOrAwaitValue()
}

理想情况是,我正在此处列出的TestCoroutineDispatcher行中寻找某些内容:https://medium.com/androiddevelopers/testing-two-consecutive-livedata-emissions-in-coroutines-5680b693cbf8

虽然我了解LiveData仅保留接收到的最后一个值,但我想知道是否有任何我们可以逐一测试排放的单位。

android unit-testing mvvm rx-java viewmodel
1个回答
0
投票

您需要在测试类中包括此规则:

@get:Rule val rule = InstantTaskExecutorRule()

和此依赖项:

testImplementation "androidx.arch.core:core-testing:2.1.0"

课程文档:

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

因此,将此与Schedulers.trampoline()结合使用作为为此调用Scheduler提供的Rx schedulerProvider.ui()应该使同步测试成为可能。

您也可以考虑使用:

implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:2.2.0"

具有扩展功能,例如toLiveData()toPublisher(),分别用于在LiveDataPublisher之间转换/适应。

© www.soinside.com 2019 - 2024. All rights reserved.