简体   繁体   English

如何从不使用Mockito模拟对象来测试异步方法?

[英]How to test async method from not mocking object with Mockito?

I want to test the code below with Mockito 我想用Mockito测试以下代码

@Override
public void getSessionList(final int carId, final ResultCallback<List<Session>> callback) {
    jobExecutor.execute(new Runnable() {
        @Override
        public void run() {
            List<SessionEntity> sessions = IDataStore.getSessionList(carId);
            final List<Session> sessionList = new ArrayList<>();
            if (sessions != null) {
                for (SessionEntity entity : sessions) {
                    sessionList.add(mapper.transform(entity));
                }
                uiThread.post(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            callback.onResult(sessionList);
                        }
                    }
                });
            } 
        }
    });
}

I tried to do something like this, but my verify methods will be executed early than runnable. 我试图做这样的事情,但是我的验证方法将比可运行的早执行。 Thread.sleep() works well for the first two verify, but how to test the result from callback.onResult which will be executed in the main thread? Thread.sleep()对于前两个验证工作得很好,但是如何测试将在主线程中执行的callback.onResult的结果?

private Repository repository // not mocked
@Mock
private IDataStore dataStore;
@Mock
private DataToDomainMapper dataToDomainMapper;
@Mock
private ResultCallback resultCallback;

@Test
public void testGetSessionListCallbackSuccess(){
    List<SessionEntity> sessionEntities = Arrays.asList(sessionEntity, sessionEntity, sessionEntity);

    given(dataStore.getSessionList(anyInt())).willReturn(sessionEntities);
    given(dataToDomainMapper.transform(any(SessionEntity.class))).willReturn(session);

    repository.getSessionList(1, resultCallback);

    verify(dataStore).getSessionList(anyInt());
    verify(dataToDomainMapper, times(3)).transform(any(SessionEntity.class));
    verify(resultCallback).onResult(any(List.class));
}

Check out tool for testing async methods called Awaitility . 检出用于测试异步方法的工具Awaitility Very handy tool, saved me a lot of time on testing async methods. 非常方便的工具,为我节省了大量测试异步方法的时间。

我相信您可以将匿名Runnable移至内部(或嵌套)类并在两部分进行拆分测试:检查jobExecutor是否开始使用相应的类实例执行;以及检查内部/嵌套类的run()方法是否按预期工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM