使用RxJava2和MutableLiveData进行单元测试

时间:2018-06-05 14:51:05

标签: android unit-testing junit kotlin rx-java2

我正在尝试对使用RxJava2的一些Android / Kotlin代码进行单元测试。代码大致如下:

val temperature = MutableLiveData<Double>()

fun save(): Single<Result<ClassifyResponse>> {
    val temp = temperature.value
    ...
    return repository.classify(request)
        .flatMap { response->
                val result: Result<ClassifyResponse> = Result.Success(response)
                Single.just(result)
        }.onErrorReturn {
                Result.Error(it)
        }
}

但是,我收到以下异常:

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

每次我进行单元测试。我读了很多tutorialsSO answers,但即使在使用RxJavaPlugins之后,我仍然无法模拟主线程调度程序,并且同样的异常占优势。

有人可以看看我的单元测试课,并建议我在这里缺少什么?

class MyViewModelTest() {

    private val repository = mock(MyRepository::class.java)

    private val immediateScheduler = object : Scheduler() {
        override fun createWorker(): Worker {
            return ExecutorScheduler.ExecutorWorker(Executor { it.run() })
        }
    }

    @Before
    fun setUp() {
        RxJavaPlugins.setInitIoSchedulerHandler { immediateScheduler }
        RxJavaPlugins.setComputationSchedulerHandler { immediateScheduler }
        RxAndroidPlugins.setInitMainThreadSchedulerHandler { immediateScheduler }
        RxAndroidPlugins.setInitMainThreadSchedulerHandler { immediateScheduler }
    }

    @Test
    fun test() {
        // given temperature view model
        val viewModel = MyViewModel(repository)
        ...

        val classifyResponse = ClassifyResponse(...)
        `when`(repository.classify(any(ClassifyRequest::class.java))).then { Single.just(classifyResponse) }

        // when sending request
        val result = viewModel.save()

        // then verify result
        val expected = Result.success(classifyResponse)

        assertEquals(expected, result)
    }
}

编辑:我注意到由于使用MutableLiveData而失败了。当我尝试访问temperature.value时,它会抱怨MainLooper线程。

1 个答案:

答案 0 :(得分:2)

您的RxJava配置正确,并且要测试@Rule @JvmField val rule = InstantTaskExecutorRule() ,您需要在测试中设置规则:

android.arch.core:core-testing

其中InstantTaskExecutorRule来自模块int solution(vector<int> &A) { // write your code in C++14 (g++ 6.2.0) if(A.size() < 2) return 0; int min_index = 0; double min = (A[0] + A[1]) / 2; for(unsigned int i = 2; i < A.size(); i++){ double temp_three = (A[i - 2] + A[ i - 1] + A[i]) / 3.0; double temp_two = (A[ i - 1] + A[i]) / 2.0; if(temp_three < min){ min = temp_three; min_index = i - 2; } if(temp_two < min){ min = temp_two; min_index = i - 1; } } return min_index; } (很快将被移至AndroidX) - 目前最新版本为1.1.1。