尝试使用 Koin DI 为 Viewmodel 创建 JUnit 测试。运行第一个测试我遇到了这个问题:
Cannot invoke setValue on a background thread
。那么我应该如何正确测试Viewmodel呢?
测试:
class TripTrackerPerspectiveViewModelTest: KoinTest {
private val viewModel: MyTrackerViewModel by inject()
@Test
fun initTest(){
Timber.d("initTest = ${viewModel.getTodayDate()}")
}
}
查看模型:
class TripTrackerPerspectiveViewModel(
private val locationManager: LocationManagerInterface,
private val settingsManager: SettingsManagerInterface): BaseViewModel() {
val currentStationIndex = MutableLiveDataUpdated<Int>().also { it.value = 0 } //error is here
}
代替:
MutableLiveDataUpdated<Int>().also { it.value = 0 }
您可以使用:
MutableLiveData<Int>().also { it.postValue(0) }
或者只是:
MutableLiveData(0)