我想为ViewModel与存储库的交互编写一个测试:
class ExampleUnitTest: KoinComponent {
val repository : Repository = mock()
val application : Application = mock()
val userRepository : UserRepository = mock()
private var tasksViewModel = MyModel(repository,application,userRepository)
// A CoroutineContext that can be controlled from tests
private val testContext = TestCoroutineContext()
// Set the main coroutines dispatcher for unit testing.
@ExperimentalCoroutinesApi
@get:Rule
var coroutinesMainDispatcherRule = ViewModelScopeMainDispatcherRule(testContext)
// Executes each task synchronously using Architecture Components.
@Rule
@JvmField
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Test
fun addition_isCorrect() {
tasksViewModel.deleteAll()
verify(repository).deleteAll()
}
}
我的ViewModel包含LiveData:
class MyModel(var repository: Repository, application: Application, val userRepository: UserRepository) :
val items = MutableLiveData<List<LiveData<Task>>>().apply {
value = emptyList()
}
}
运行测试时,出现以下错误:
java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked.
和对
的引用value = emptyList()
在我的ViewModel里面
我删除此行时
value = emptyList()
它运作良好,但是如何处理而不删除此行