I have created a sample Login screen App with MVVM pattern,Android Lifecycle components and LiveData.On Repository,I have simulated some task using Handler with delay.How do I test the ViewModel and Repository method with Handler.As it is asynchronous process,how to get LiveData value after runnable return value?
@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;
}