We have following code for ViewModel :
class MyViewModel : ViewModel() {
private val users: MutableLiveData<List<User>> by lazy {
MutableLiveData().also {
loadUsers()
}
}
fun getUsers(): LiveData<List<User>> {
return users
}
private fun loadUsers() {
// Do an asynchronous operation to fetch users.
}
}
I want to have a unit test for this code :
@Test
fun loadUsers() {
val user= User("name")
val observableResponse =
Observable.just(api.UserWrapper(Lists.newArrayList(user)))
`when`(api.loadUsers()).thenReturn(observableResponse)
with(viewModel) {
with(this.users.value!!) {
assertFalse(isEmpty())
assertTrue(size == 1)
}
}
}
But it does not passing the test. It is due to lazy loading :
private val users: MutableLiveData<List<User>> by lazy {
MutableLiveData().also {
loadUsers()
}
}
What could be the solution?
Here is the error :
NullPointerException
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:411)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at io.reactivex.Observable.subscribe(Observable.java:12034)
at io.reactivex.Observable.subscribe(Observable.java:12016)
at io.reactivex.Observable.subscribe(Observable.java:11945)
at com.sample.android.tmdb.ui.detail.DetailViewModel$_cast$2.invoke(DetailViewModel.kt:25)
at com.sample.android.tmdb.ui.detail.DetailViewModel$_cast$2.invoke(DetailViewModel.kt:12)
at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
at com.sample.android.tmdb.ui.detail.DetailViewModel.get_cast(DetailViewModel.kt)
at com.sample.android.tmdb.ui.detail.DetailViewModel.access$get_cast$p(DetailViewModel.kt:12)
at com.sample.android.tmdb.ui.detail.DetailViewModel$_cast$2$$special$$inlined$also$lambda$4.accept(DetailViewModel.kt:26)
at com.sample.android.tmdb.ui.detail.DetailViewModel$_cast$2$$special$$inlined$also$lambda$4.accept(DetailViewModel.kt:12)