单元测试 viewModel 和 livedata Mockito android

Unit testing the viewModel and livedata Mockito android

我正在尝试使用 Mockito 为我的视图模型实施单元测试, 当我的调试器要将值分配给实时数据时,它会因错误 NullPointerException 而崩溃,即我们无法将值分配给实时数据

我的视图-模型-测试Class

@Test
fun getNews() {

    Mockito.`when`(mainRepository.getNews()).thenReturn(Observable.just(getMockResponse()))
    //It is working good

    Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(true)
    //It is working good

    viewModel.getNews()

    assertEquals(Resource.success(getList()), viewModel.newsResponse.value)
}

我的视图模型

 val newsResponse by lazy { SingleLiveEvent<Resource<List<RowsItem>>>() }

        fun getNews() {
        if (!networkHelper.isNetworkConnected()) { //It is true as we macked in Test Clas
            newsResponse.value = Resource.error(AppError.NetworkError)
            return
        }
        newsResponse.value = Resource.loading() // Crashing here when we are assigning value to live data: newsResponse
        val api = mainRepository.getNews().map {
            it.rows
        }

        val disposable = api.subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                { result -> handleResults(result) },
                { error -> handleError(error) },
            )

        compositeDisposable.add(disposable)
    }


     private fun handleResults(list: ArrayList<RowsItem>?) {
         if (list != null) {
             newsResponse.value = Resource.success(list)
 
         } else {
             newsResponse.value = Resource.error(AppError.CommonError)
         }
     }

      private fun handleError(t: Throwable?) {
          newsResponse.value = Resource.error(t?.failureAppError() ?: AppError.CommonError)
      }

错误

java.lang.NullPointerException 在 androidx.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:77) 在 androidx.arch.core.executor.ArchTaskExecutor.isMainThread(ArchTaskExecutor.java:116) 在 androidx.lifecycle.LiveData.assertMainThread(LiveData.java:486) 在 androidx.lifecycle.LiveData.setValue(LiveData.java:306) 在 androidx.lifecycle.MutableLiveData.setValue(可变LiveData.java:50) 在 com.lifex.proficiencyexercise.repo.utils.SingleLiveEvent.setValue(SingleLiveEvent.java:28) 在 com.lifex.proficiencyexercise.ui.MainActivityViewModel.getNews(MainActivityViewModel.kt:37) 在 com.lifex.proficiencyexercise.ui.MainActivityViewModelTest.getNews(MainActivityViewModelTest.kt:45) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(本机方法) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.base/java.lang.reflect.Method.invoke(Method.java:566) 在 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(框架Method.java:59) 在 org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 在 org.junit.runners.model.FrameworkMethod.invokeExplosively(框架 Method.java:56) 在 org.junit.internal.runners.statements.InvokeMethod.evaluate(调用Method.java:17) 在 org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) 在 org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:54) 在 org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) 在 org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100) 在 org.junit.runners.ParentRunner.运行 叶(ParentRunner.java:366) 在 org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103) 在 org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63) 在 org.junit.runners.ParentRunner$4.run(ParentRunner.java:331) 在 org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79) 在 org.junit.runners.ParentRunner.运行 儿童 (ParentRunner.java:329) 在 org.junit.runners.ParentRunner.access$100(ParentRunner.java:66) 在 org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293) 在 org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) 在 org.junit.runners.ParentRunner.运行(ParentRunner.java:413) 在 org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:99) 在 org.mockito.internal.runners.DefaultInternalRunner.运行(DefaultInternalRunner.java:105) 在 org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:40) 在 org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163) 在 org.junit.runner.JUnitCore.run(JUnitCore.java:137) 在 com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69) 在 com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33) 在 com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220) 在 com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

进程已完成,退出代码为 -1

只需要在测试中添加规则class

@Rule
@JvmField
var testSchedulerRule = RxImmediateSchedulerRule() //For Retrofit

@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()//For LiveData

RxImmediateSchedulerRule 是自定义 class 扩展 TestRule

class RxImmediateSchedulerRule : TestRule {

private val immediateScheduler = object : Scheduler() {
    @NonNull
    override fun scheduleDirect(@NonNull run: Runnable, delay: Long, @NonNull unit: TimeUnit): Disposable {
        // Hack to prevent stack overflows in unit tests when scheduling with a delay;
        return super.scheduleDirect(run, 0, unit)
    }

    @NonNull
    override fun createWorker(): Worker {
       return ExecutorScheduler.ExecutorWorker(Executor { it.run() })
    }
}

@NonNull
override fun apply(@NonNull base: Statement, @NonNull description: Description): Statement {
    return object : Statement() {
        @Throws(Throwable::class)
        override fun evaluate() {
            RxJavaPlugins.setInitIoSchedulerHandler { immediateScheduler }
            RxJavaPlugins.setInitComputationSchedulerHandler { immediateScheduler }
            RxJavaPlugins.setInitNewThreadSchedulerHandler { immediateScheduler }
            RxJavaPlugins.setInitSingleSchedulerHandler { immediateScheduler }
            RxAndroidPlugins.setInitMainThreadSchedulerHandler { immediateScheduler }

            try {
                base.evaluate()
            } finally {
                RxJavaPlugins.reset()
                RxAndroidPlugins.reset()
            }
        }
    }
}}

最后我的测试 Class 看起来像

 @RunWith(MockitoJUnitRunner::class)
 class MainActivityViewModelTest : TestCase() {


private val networkHelper = Mockito.mock(NetworkHelper::class.java)

private val mainRepository = Mockito.mock(MainRepository::class.java)

private val viewModel = MainActivityViewModel(networkHelper, mainRepository)

@Rule
@JvmField
var testSchedulerRule = RxImmediateSchedulerRule() //For Retrofit

@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()//For LiveData


@Before
public override fun setUp() {

}

@Test
fun getNews() {
    Mockito.`when`(mainRepository.getNews()).thenReturn(Observable.just(getMockResponse()))
    //It is working good
    Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(true)

    //It is working good
    viewModel.getNews()

    assertEquals(Resource.success(getList()), viewModel.newsResponse.value)


}

private fun getMockResponse(): ApiResponse<ArrayList<RowsItem>> {
    return ApiResponse("Response Success", getList())
}

private fun getList(): ArrayList<RowsItem> {
    val rowsItem = RowsItem("ImageHref", "Desc", "Title")
    val list = ArrayList<RowsItem>()
    list.add(rowsItem)
    return list
}}