如何在异步可运行返回值之后测试Android LiveData值

如何在异步可运行返回值之后测试Android LiveData值,android,mvvm,junit,mockito,junit4,Android,Mvvm,Junit,Mockito,Junit4,我创建了一个带有MVVM模式、Android Lifecycle组件和LiveData的示例登录屏幕应用程序。在Repository上,我使用延迟处理程序模拟了一些任务。如何使用处理程序测试ViewModel和Repository方法。由于这是一个异步过程,如何在runnable返回值之后获得LiveData值 @测试 公共无效检查\u do\u登录(){ final Handler=mock(Handler.class); 当(handler.postDelayed(any(Runnable

我创建了一个带有MVVM模式、Android Lifecycle组件和LiveData的示例登录屏幕应用程序。在Repository上,我使用延迟处理程序模拟了一些任务。如何使用处理程序测试ViewModel和Repository方法。由于这是一个异步过程,如何在runnable返回值之后获得LiveData值

@测试
公共无效检查\u do\u登录(){
final Handler=mock(Handler.class);
当(handler.postDelayed(any(Runnable.class)、anyLong())
.thenAnswer(新答案){
@凌驾
公共布尔应答(invocationMock调用)抛出可丢弃的{
Runnable=invocation.getArgument(0);
runnable.run();
//schedule(runnable,anyInt(),TimeUnit.ms);
返回true;
}
});
LiveData stringLiveData=mLoginFragmentViewModel.doLogin(“username@gmail.com", "password@123");
LifecycleOwner LifecycleOwner=mock(LifecycleOwner.class);
stringLiveData.observe(lifecycleOwner,新观察者(){
@凌驾
公共void onChanged(@Nullable String s){
assertEquals(“登录成功”);
}
});
}

public MutableLiveData登录(字符串用户名、字符串密码){
final MutableLiveData loginResponseLiveData=新的MutableLiveData();
new Handler().postDelayed(new Runnable()){
@凌驾
公开募捐{
//将用户名、密码发送到服务器,
//出于测试目的,在处理程序上设置延迟以模拟此过程
loginResponseLiveData.setValue(“登录成功”);
}
},5*1000);
//返回要在UI上观察的MutableLiveData对象
返回loginResponseLiveData;
}
@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;
    }