I am trying to write unit test for my ViewModel class. In this case, I have an activity that when created, it subscribes to my repo (LiveData from viewModel) and retrieves a list of Github repositories from network or database.
What should I be testing here? I tried to write two test methods:
dontFetchWithoutObservers which fails with the following:
[![enter image description here][1]][1]
fetchWhenObserved which fails with the following: [![enter image description here][2]][2]
Here's my ViewModel class:
class MainViewModel @ViewModelInject constructor(mainRepository: MainRepository) : ViewModel() {
val repo: LiveData<Resource<List<Repository>>> = mainRepository.getRepositories()
}
And my ViewModel test class:
@RunWith(JUnit4::class)
class MainViewModelTest {
@Rule
@JvmField
val instantTaskExecutorRule = InstantTaskExecutorRule()
private val mainRepository = mock(MainRepository::class.java)
private lateinit var mainViewModel: MainViewModel
@Before
fun init() {
mainViewModel = MainViewModel(mainRepository)
}
@Test
fun dontFetchWithoutObservers() {
verify(mainRepository, never()).getRepositories()
}
@Test
fun fetchWhenObserved() {
mainViewModel.repo.observeForever(mock())
verify(mainRepository).getRepositories()
}
}
you are not mocking the getRepositories
method and in fact the error you get is: NPE. Provide a mock for getRepositories
method.
`when`(mainRepository.getRepositories()).thenReturn(YourObject)
Also I would go and check the contents of getRepositories
instead of just verifying that it is being invoked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.