android - 为 ViewModel 创建单元测试
问题描述
我最近完成了这个(下面的链接)codelabs 教程,其中介绍了如何在 Kotlin 中使用 LiveData 和 Databinding 实现 Room。
https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/
https://github.com/googlecodelabs/android-room-with-a-view/tree/kotlin
在此之后,我想围绕 ViewModel 编写一些测试,但是,存储代码的 GitHub 存储库不包含任何内容(它围绕 DAO 进行了一些测试,这不是我现在感兴趣的)。
我尝试测试的 ViewModel 如下所示:
class WordViewModel(application: Application) : AndroidViewModel(application) {
private val repository: WordRepository
// Using LiveData and caching what getAlphabetizedWords returns has several benefits:
// - We can put an observer on the data (instead of polling for changes) and only update the
// the UI when the data actually changes.
// - Repository is completely separated from the UI through the ViewModel.
val allWords: LiveData<List<Word>>
init {
val wordsDao = WordRoomDatabase.getDatabase(application, viewModelScope).wordDao()
repository = WordRepository(wordsDao)
allWords = repository.allWords
}
/**
* Launching a new coroutine to insert the data in a non-blocking way
*/
fun insert(word: Word) = viewModelScope.launch(Dispatchers.IO) {
repository.insert(word)
}
}
我的 ViewModel 测试类如下所示:
@RunWith(JUnit4::class)
class WordViewModelTest {
private val mockedApplication = mock<Application>()
@Test
fun checkAllWordsIsEmpty() {
val vm = WordViewModel(mockedApplication)
assertEquals(vm.allWords, listOf<String>())
}
}
我收到一条错误消息,java.lang.IllegalArgumentException: Cannot provide null context for the database.
此错误然后指向 WordViewModel: 中的这一行val wordsDao = WordRoomDatabase.getDatabase(application, viewModelScope).wordDao()
。为了让它不会崩溃,我相信我需要模拟 ViewModel 中的很多内容,我对此很好。
我希望能够运行上面的测试,并且在将来,我还想在repository.allWords
调用时模拟返回数据列表。但是,我不知道该怎么做。所以我的问题是,如何模拟 WordViewModel 中的以下几行以允许我这样做?
val wordsDao = WordRoomDatabase.getDatabase(application, viewModelScope).wordDao()
repository = WordRepository(wordsDao)
allWords = repository.allWords
解决方案
推荐阅读
- php - 显示当前选择的产品变体
- c++ - Ruby C 扩展 - TypedData_Get_Struct 调用上的 TypeError 不是类型错误
- php - 如何在whatsapp消息中制作一些文本作为链接
- tensorflow - 你能用'keras.utils.to_categorical'在张量流中映射一个数据集吗?
- c# - 如何反序列化其类型被修改为抽象类的二进制格式对象?
- c# - 基于嵌套列表对列表进行排序
- maps - 如何在集水区分割地图(多边形收集特定点的最近点)
- java - 使用 Java 获取请求
- sql - 计算日期的累积总和,但不包括以后删除的数据
- azure - 如何使用 terraform 创建 azure 事件网格系统主题?