相关疑难解决方法(0)

在 init 块中使用 postValue 时出现 LiveData 单元测试错误

我正在尝试使用实时数据为视图模型编写单元测试。

登录视图模型.kt

class LoginViewModel @Inject constructor(
    val context: Context
): ViewModel() {
    val username = MutableLiveData<String>()
    val password = MutableLiveData<String>()
    val isLoginButtonEnabled = MediatorLiveData<Boolean>().apply {
        fun combineLatest(): Boolean {
            return !(username.value.isNullOrEmpty() || password.value.isNullOrEmpty())
        }
        addSource(username) { this.value = combineLatest() }
        addSource(password) { this.value = combineLatest() }
    }

    init {
        username.postValue("test")
        password.postValue("test")
    }
}
Run Code Online (Sandbox Code Playgroud)

登录ViewModelTest.kt

@RunWith(MockitoJUnitRunner::class)
class LoginViewModelTest {
    @Rule
    @JvmField
    val instantTaskExecutorRole = InstantTaskExecutorRule()

    private val context = mock(Context::class.java)
    private val loginViewModel = LoginViewModel(context)

    @Test
    fun loginButtonDisabledOnEmptyUsername() {
        val observer …
Run Code Online (Sandbox Code Playgroud)

android kotlin android-livedata android-viewmodel android-architecture-components

8
推荐指数
2
解决办法
4498
查看次数