单元测试时出现此错误:“从未设置LiveData值。”
我尝试测试视图模型的getStudents()方法,如下所示:
学生视图模型:
@HiltViewModel
class StudentViewModel @Inject constructor(
private val getStudentsUseCase: GetStudentsUseCase
) : ViewModel() {
private val _studentLD = MutableLiveData<List<Student>>()
val studentLD: LiveData<List<Student>> = _studentLD
private val _errorLD = MutableLiveData<String>()
val errorLD: LiveData<String> = _errorLD
fun getStudents() {
viewModelScope.launch {
var result = getStudentsUseCase.execute()
result.onSuccess {
_studentLD.value = it
}.onFailure {
_errorLD.value = it.message.toString()
}
}
}
}
学生视图模型测试:
@OptIn(ExperimentalCoroutinesApi::class)
class StudentViewModelTest {
private lateinit var viewModel: StudentViewModel
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
@get:Rule
var mainCoroutineRule = MainCoroutineRule()
@Mock
private lateinit var getStudentsUseCase: GetStudentsUseCase
private var studentList = listOf(
Student("Max", "122d"),
Student("Steven", "012s")
)
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
viewModel = StudentViewModel(getStudentsUseCase)
}
@Test
fun getStudentsSuccess() = runTest {
Mockito.`when`(getStudentsUseCase.execute()).thenReturn(Result.success(studentList))
viewModel.getStudents()
val value = viewModel.studentLD.getOrAwaitValueTest()
assertEquals(value, studentList)
}
}
我做错了什么?我也有一个LiveDataTest类,其中定义了getOrAwaitValueTest()方法。提前感谢
编辑:此外,getOrAwaitValueTest()方法在此处定义如下:
@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun <T> LiveData<T>.getOrAwaitValueTest(
time: Long = 2,
timeUnit: TimeUnit = TimeUnit.SECONDS,
afterObserve: () -> Unit = {}
): T {
var data: T? = null
val latch = CountDownLatch(1)
val observer = object : Observer<T> {
override fun onChanged(o: T?) {
data = o
latch.countDown()
this@getOrAwaitValueTest.removeObserver(this)
}
}
this.observeForever(observer)
try {
afterObserve.invoke()
// Don't wait indefinitely if the LiveData is not set.
if (!latch.await(time, timeUnit)) {
throw TimeoutException("LiveData value was never set.")
}
} finally {
this.removeObserver(observer)
}
@Suppress("UNCHECKED_CAST")
return data as T
}
1条答案
按热度按时间yzxexxkh1#
我找到了一个解决办法:要使其正常工作,您需要添加advanceUntilIdle()方法。
立即执行所有挂起的任务,并将虚拟时钟时间提前到最后一个延迟。如果由于虚拟时间提前而调度了新任务,则将在advanceUntilIdle返回之前执行这些任务。