嗨,我正试图测试我的视图模型中的livedata,我已经编写了测试以验证存储库调用是否已进行
我如何检查在这种情况下是否活动数据对象,以及我应该为viewModel
中的代码编写哪些额外的测试用例谢谢R
MainActivityViewModel
class MainActivityViewModel @Inject constructor(
private val dataRepository: DataRepository
): ViewModel() {
val _charactersLiveData = MutableLiveData<Result<ArrayList<Character>>>()
val charactersLiveData: LiveData<Result<ArrayList<Character>>> = _charactersLiveData
fun fetchCharacters() {
viewModelScope.launch {
_charactersLiveData.value = dataRepository.getCharacters()
}
}
}
MainActivityViewModelTest
@RunWith(MockitoJUnitRunner::class)
class MainActivityViewModelTest {
@get:Rule
val coroutineRule = MainCoroutineRule()
@Mock
private lateinit var dataRepository: DataRepository
@InjectMocks
private lateinit var mainActivityViewModel: MainActivityViewModel
@Test
fun fetchCharacters() {
runBlockingTest {
mainActivityViewModel.fetchCharacters()
verify(dataRepository).getCharacters()
}
}
}
您可以参考这篇文章:https://medium.com/androiddevelopers/unit-testing-livedata-and-other-common-observability-problems-bb477262eb04
这里的主要思想是:
- Mock
dataRepository
- 当
dataRepository
调用getCharacters()
时,应该返回测试值。例:listOf('a')
- 执行
mainActivityViewModel.fetchCharacters()
- 期望您的实时数据的值
assertEquals(mainActivityViewModel.charactersLiveData.getOrAwaitValue(), listOf('a'))
尝试这个,如果有任何问题,然后让我知道。我已经试着根据你的类和数据做,但如果你需要,然后可以改变。
@RunWith(MockitoJUnitRunner::class)
class MainActivityViewModelTest {
@get:Rule
val coroutineRule = MainCoroutineRule()
@Mock
private lateinit var dataRepository: DataRepository
@InjectMocks
private lateinit var mainActivityViewModel: MainActivityViewModel
@Mock
private lateinit var dataObserver: Observer<Result<List<Character>>>
@Test
fun fetchCharacters() {
runBlockingTest {
Mockito.`when`(datarepository).getcharacter()
.thenreturn(Result.success(listOf(Character (
Name=A,
Type=hero))))
mainActivityViewModel.fetchCharacters()
mainActivityViewModel.charactersLiveData.observeForever(dataObserver)
Mockito.verify(dataRepository).getCharacters()
Mockito.verify(dataObserver).onChanged(Result.success(listOf(Character (
Name=A,
Type=hero))))
mainActivityViewModel.charactersLiveData.removeObserver(dataObserver)
}
}
}