用RxJava 2和MutableLiveData进行单元测试?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (323)

我正在尝试对一些使用RxJava 2的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.

有人能看看我的单元测试课并建议我在这里遗漏了什么吗?

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)
    }
}
提问于
用户回答回答于

你的RxJava配置正确,用于测试MutableLiveData你需要在测试中设置规则:

@Rule
@JvmField
val rule = InstantTaskExecutorRule()

扫码关注云+社区

领取腾讯云代金券