如何在异步runnable返回值后JUnit测试Android LiveData值

时间:2017-07-19 12:48:52

标签: android mvvm junit mockito junit4

我创建了一个带有MVVM模式,Android生命周期组件和LiveData.On存储库的示例登录界面应用程序,我使用Handler模​​拟了一些延迟的任务。如何使用Handler测试ViewModel和Repository方法。因为它是异步的进程,如何在runnable返回值后得到LiveData值?

https://github.com/rramprasad/MVVMArchitectureApp/blob/master/app/src/test/java/com/rramprasad/testingsample/LoginFragmentViewModelTest.java

@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");
            }
        });
    }

https://github.com/rramprasad/MVVMArchitectureApp/blob/master/app/src/main/java/com/rramprasad/testingsample/repository/LoginRepository.java

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;
    }

0 个答案:

没有答案