Ram*_*sad 5 junit android mvvm junit4 mockito
我创建了一个带有 MVVM 模式、Android 生命周期组件和 LiveData 的示例登录屏幕应用程序。在存储库中,我使用延迟处理程序模拟了一些任务。如何使用处理程序测试 ViewModel 和存储库方法。由于它是异步过程,如何在可运行返回值后获取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");
}
});
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1090 次 |
| 最近记录: |