我最近完成了此代码实验室教程(下面的链接),该教程逐步介绍了如何在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看起来像这样:
var version = Windows.ApplicationModel.Package.Current.Id.Version;
applicationVersion = string.Format("{0}.{1}.{2}.{3}",
version.Major,
version.Minor,
version.Build,
version.Revision);
我的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)
}
}
我收到一条错误消息,说@RunWith(JUnit4::class)
class WordViewModelTest {
private val mockedApplication = mock<Application>()
@Test
fun checkAllWordsIsEmpty() {
val vm = WordViewModel(mockedApplication)
assertEquals(vm.allWords, listOf<String>())
}
}
,然后此错误指向WordViewModel中的这一行:java.lang.IllegalArgumentException: Cannot provide null context for the database.
。为了避免崩溃,我相信我需要对ViewModel中的很多东西进行模拟,我对此很满意。
我希望能够在以后进行测试,并且还希望在调用val wordsDao = WordRoomDatabase.getDatabase(application, viewModelScope).wordDao()
时模拟返回数据列表。但是,我不确定如何执行此操作。所以我的问题是,如何从WordViewModel中模拟以下几行以允许我执行此操作?
repository.allWords