我创建了一个带有MVVM模式,Android生命周期组件和LiveData.On存储库的示例登录界面应用程序,我使用Handler模拟了一些延迟的任务。如何使用Handler测试ViewModel和Repository方法。因为它是异步的进程,如何在runnable返回值后得到LiveData值?
@Test
public void check_do_login(){
final Handler handler = mock(Handler.class);
when(handler.postDelayed(any(Runnable.class),anyLong()))
.thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
Runnable runnable = invocation.getArgument(0);
runnable.run();
//mainThread.schedule(runnable, anyInt(), TimeUnit.MILLISECONDS);
return true;
}
});
LiveData<String> stringLiveData = mLoginFragmentViewModel.doLogin("username@gmail.com", "password@123");
LifecycleOwner lifecycleOwner = mock(LifecycleOwner.class);
stringLiveData.observe(lifecycleOwner, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
assertEquals(s,"Login success");
}
});
}
public MutableLiveData<String> login(String username, String password) {
final MutableLiveData<String> loginResponseLiveData = new MutableLiveData<String>();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//send username,password to server,
// For testing purpose,set delay on handler to simulate this process
loginResponseLiveData.setValue("Login success");
}
},5*1000);
//Return MutableLiveData object to observe on UI
return loginResponseLiveData;
}