我正在尝试使用LiveData测试ViewModel,但是存在一些问题。我无法得到它。我的测试只在一种情况下不通过 - HashMap的最后一个元素的值为true。但测试通过任何其他案件
这是我的测试没有通过
class PermissionsViewModelTest{
@get:Rule
var rule: TestRule = InstantTaskExecutorRule()
lateinit var viewModel: PermissionsViewModel
@Before
fun setUp() {
viewModel = PermissionsViewModel()
}
//Omited
@Test
fun `Should post false if permissions is not granted`() {
val permissions = hashMapOf(
Pair("123", true),
Pair("123", false),
Pair("123", true),
Pair("123", true),
Pair("123", true)
)
val observer = Mockito.mock(Observer::class.java) as Observer<Boolean>
viewModel.isAllPermissionsGranted.observeForever(observer)
viewModel.checkPermissions(permissions)
assertFalse(viewModel.isAllPermissionsGranted.value!!)
}
//Omitted
}
这是我的ViewModel
class PermissionsViewModel : ViewModel() {
var isAllPermissionsGranted = MutableLiveData<Boolean>().apply {
value = null
}
fun checkPermissions(permissionsResult: HashMap<String, Boolean>) {
var isAllPermissionsGranted = true
permissionsResult.values.forEach { isGranted ->
if (!isGranted) {
isAllPermissionsGranted = false
return@forEach
}
}
this.isAllPermissionsGranted.postValue(isAllPermissionsGranted)
}
}
我是否以错误的方式测试LiveData?或者测试LiveData有什么问题吗?
首先,我不确定您是否使用该hashmap进行测试,因为它具有相同的密钥,因此它可能会使用最后一对。其次,对于实时数据(因为它是异步的)我发现使用阻塞可观察扩展非常有帮助。这是阻塞可观察扩展的工作代码:
class PermissionsViewModelTest{
@get:Rule
var rule: TestRule = InstantTaskExecutorRule()
lateinit var viewModel: PermissionsViewModel
@Before
fun setUp() {
viewModel = PermissionsViewModel()
}
//Omited
@Test
fun `Should post false if permissions is not granted`() {
val permissions = hashMapOf(
Pair("123", true),
Pair("124", true),
Pair("125", false),
Pair("126", true),
Pair("127", true)
)
val grantedObserver = viewModel.isAllPermissionsGranted
viewModel.checkPermissions(permissions)
val value = grantedObserver.blockingObserve() // extension below
assertFalse(value!!)
}
//Omited
}
class PermissionsViewModel : ViewModel() {
var isAllPermissionsGranted = MutableLiveData<Boolean>().apply {
value = null
}
fun checkPermissions(permissionsResult: HashMap<String, Boolean>) {
val isAllPermissionsGranted = permissionsResult.values.all{it}
this.isAllPermissionsGranted.postValue(isAllPermissionsGranted)
}
}
// blocking observe extension:
fun <T> LiveData<T>.blockingObserve(): T? {
var value: T? = null
val latch = CountDownLatch(1)
val innerObserver = Observer<T> {
value = it
latch.countDown()
}
observeForever(innerObserver)
latch.await(2, TimeUnit.SECONDS)
return value
}