我得到了mockito想要但没有被调用。我不知道该怎么做,因为我是新来的:)。顺便说一句,当我在真实设备中运行代码时,它还可以。
需要但未调用:observer.onChanged(true);
测试类
@RunWith(MockitoJUnitRunner::class)
class LoginViewModelTest {
var loginViewModel: LoginViewModel? = null
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Mock
lateinit var observer: Observer<Boolean>
@Mock
lateinit var dataManager: DataManager
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
loginViewModel = LoginViewModel(dataManager)
}
@Test
fun testApiFetchDataSuccess() {
loginViewModel?.liveData?.observeForever(observer)
loginViewModel?.login("test", "1234")
verify(observer)?.onChanged(true)
}
}
视图模型类
class LoginViewModel(dataManager: DataManager?) : BaseViewModel() {
var liveData: MutableLiveData<Boolean>
var dataManager: DataManager? = dataManager
init {
liveData = MutableLiveData()
}
fun login(email: String, password: String) {
dataManager?.getFireStoreManager()?.login(email, password)?.get()?.addOnSuccessListener {
if (it.documents.size > 0) {
val data = it.documents[0].toObject(User::class.java)
liveData.postValue(true)
} else {
liveData.postValue(false)
}
}?.addOnFailureListener {
liveData.postValue(false)
}
}
}