Android ViewModel单元测试:RXJAVA ONSUCCESS提供NullPoInterException



我正在尝试单元测试我的ViewModel类,但是当我运行测试时,我会在一次性OnSuccess方法中获得NullPointerException,但我不明白为什么。因此,我测试的方法总是返回null。

这是我的测试类CityListViewModelTest.kt的代码:

@RunWith(JUnit4::class)
class CityListViewModelTest {
    @Rule
    @JvmField
    val rule = InstantTaskExecutorRule()
    @Mock
    private lateinit var repository: ForecastRepository
    @InjectMocks
    private lateinit var viewModel: CityListViewModel

    @Before @Throws fun setUp(){
        RxAndroidPlugins.setInitMainThreadSchedulerHandler{Schedulers.trampoline()}
RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }
        MockitoAnnotations.initMocks(this)
    }
    @Test
    fun getCities() {
        val response = getMockedCities(5)
        `when`(repository.getCities(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble()))
            .thenReturn(Single.just(response))
        val result = viewModel.getCities(0.0,0.0)
        verify(repository).getCities(0.0,0.0)
        verify(repository).getCache() //should be called but isn't
        assertEquals(response.list,result.value) //result.value should be a list of 5 mocked cities but is null
    }
    fun getMockedCities(count : Int) : OpenWeatherCycleDataResponse {
        val cities = ArrayList<City>()
        for (i in 0..count) {
            val city = mock(City::class.java)
            cities.add(city)
        }
        return OpenWeatherCycleDataResponse(cities)
    }
}

和我的ViewModel类CityListViewModel.kt

class CityListViewModel @Inject constructor(private var forecastRepo: ForecastRepository):ViewModel() {
    //@Inject lateinit
    var cities : MutableLiveData<List<City>> = MutableLiveData()
    //@Inject lateinit
     var disposable : CompositeDisposable = CompositeDisposable()

    fun getCities(lat: Double,lon:Double): LiveData<List<City>> {
        disposable.add(forecastRepo.getCities(lat,lon).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(object: DisposableSingleObserver<OpenWeatherCycleDataResponse>(){
                override fun onSuccess(t: OpenWeatherCycleDataResponse) {
                    forecastRepo.getCache().saveCities(t.list)
                    cities.value = t.list
                }
                override fun onError(e: Throwable) {
                    Timber.e(e.localizedMessage)
                }
            }))
        return cities
    }
    fun getCityByName(cityName: String): LiveData<City>{
        val searchedCity = MutableLiveData<City>()
        disposable.add(forecastRepo.getCityByName(cityName).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(object: DisposableSingleObserver<City>(){
                override fun onSuccess(t: City) {
                    searchedCity.value = t
                    forecastRepo.getCache().saveCities(listOf(t))
                }
                override fun onError(e: Throwable) {
                    Timber.e(e.localizedMessage)
                }
            }))
        return searchedCity
    }
    override fun onCleared() {
        super.onCleared()
        disposable.clear()
    }
}

这是日志:

java.lang.NullPointerException
    at com.example.zach.weatherapp.viewModel.CityListViewModel$getCities$1.onSuccess(CityListViewModel.kt:30)
    at com.example.zach.weatherapp.viewModel.CityListViewModel$getCities$1.onSuccess(CityListViewModel.kt:27)
    at io.reactivex.internal.operators.single.SingleObserveOn$ObserveOnSingleObserver.run(SingleObserveOn.java:81)
    at io.reactivex.internal.schedulers.TrampolineScheduler.scheduleDirect(TrampolineScheduler.java:52)
    at io.reactivex.internal.operators.single.SingleObserveOn$ObserveOnSingleObserver.onSuccess(SingleObserveOn.java:64)
    at io.reactivex.internal.operators.single.SingleSubscribeOn$SubscribeOnObserver.onSuccess(SingleSubscribeOn.java:68)
    at io.reactivex.internal.operators.single.SingleJust.subscribeActual(SingleJust.java:30)
    at io.reactivex.Single.subscribe(Single.java:3096)
    at io.reactivex.internal.operators.single.SingleSubscribeOn$SubscribeOnObserver.run(SingleSubscribeOn.java:89)
    at io.reactivex.internal.schedulers.TrampolineScheduler.scheduleDirect(TrampolineScheduler.java:52)
    at io.reactivex.internal.operators.single.SingleSubscribeOn.subscribeActual(SingleSubscribeOn.java:37)
    at io.reactivex.Single.subscribe(Single.java:3096)
    at io.reactivex.internal.operators.single.SingleObserveOn.subscribeActual(SingleObserveOn.java:35)
    at io.reactivex.Single.subscribe(Single.java:3096)
    at io.reactivex.Single.subscribeWith(Single.java:3140)
    at com.example.zach.weatherapp.viewModel.CityListViewModel.getCities(CityListViewModel.kt:27)
    at com.example.zach.weatherapp.viewModel.CityListViewModelTest.getCities(CityListViewModelTest.kt:58)

一旦称为:

// CityListViewModelTest
val result = viewModel.getCities(0.0,0.0)

CityListViewModel将订阅forecastRepo.getCities(),因此verify(repository).getCities(0.0,0.0)通过。

但是,不能保证forecastRepo.getCache()verify(repository).getCache()之前会被调用,因为forecastRepo.getCities()在单独的线程上运行。在您的测试代码中,您需要使用Testscheduler等待IO调度程序中的操作完成。

旁注:

在ViewModels中,.observeOn(AndroidSchedulers.mainThread())似乎在这里做得不多,因为ViewModels独立于Android Lifecycles。您可以使用postValue()而不是使用setValue()来从背景线程更新MutableLiveData


更新:

尝试使用以下方式:

@Rule
@JvmField
val rule = InstantTaskExecutorRule()
@Mock
lateinit var observer: Observer<List<City>>
@Test
fun getCities() {
    val response = getMockedCities(5)
    `when`(repository.getCities(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble()))
        .thenReturn(Single.just(response))
    viewModel.getCities(0.0,0.0).observeForever(observer)
    verify(repository).getCities(0.0,0.0)
    verify(repository).getCache()
    // assertEquals(response.list,result.value) //result.value should be a list of 5 mocked cities but is null
    verify(observer).onChanged(reponse.list)
}

getCache()getCache().saveCities()也可能是问题。如果上述代码不起作用,请尝试嘲笑这些。

通过手工创建虚拟响应解决的问题。getMockedCities()返回一系列带有空变量的城市对象(如预期的那样),但我的城市对象的变量并非不可用。另外,我不得不模拟repository.getCache()

相关内容

  • 没有找到相关文章

最新更新