我一直在模拟一个函数ResultSetFuture的测试,我使用Github(可以工作)的一个例子来测试ResultSetFuture,但是我测试/模拟的代码使用Futures#successfulAsList
,如here所示。因此,在第34行,测试暂停,永不完成。下面显示的代码是暂停测试的一部分。
ResultSetFuture future = Mockito.mock(ResultSetFuture.class);
Mockito.doReturn(result).when(future).get();
Mockito.doReturn(future).when(session).executeAsync(Mockito.anyString());
ResultSetFuture resultF = session.executeAsync("select value from table where key='a'");
Future<List<ResultSet>> data = Futures.successfulAsList(new ArrayList(){{ add(resultF); }});
List finished = data.get(); // <---- The test stops here
你需要在isDone
中模拟future
方法来指示执行完成并避免代码停止。
ResultSetFuture future = Mockito.mock(ResultSetFuture.class);
Mockito.doReturn(result).when(future).get();
Mockito.doReturn(future).when(session).executeAsync(Mockito.anyString());
Mockito.doReturn(true).when(future).isDone(); //<-- mock to avoid halting
ResultSetFuture resultF = session.executeAsync("select value from table where key='a'");
Future<List<ResultSet>> data = Futures.successfulAsList(Collections.singletonList(resultF));
List finished = data.get(); // <---- The test stops here
你必须模拟isDone
和addListener
方法:
ResultSetFuture future = Mockito.mock(ResultSetFuture.class);
Mockito.doReturn(result).when(future).get();
Mockito.doReturn(true).when(future).isDone();
Mockito.doAnswer(i -> {
i.getArgumentAt(1, Executor.class).execute(i.getArgumentAt(0, Runnable.class));
return null;
}).when(future).addListener(any(), any());
Mockito.doReturn(future).when(session).executeAsync(Mockito.anyString());
ResultSetFuture resultF = session.executeAsync("select value from table where key='a'");
Future<List<ResultSet>> data = Futures.successfulAsList(Collections.singletonList(resultF));
List finished = data.get();
addListener
是必需的,因为Futures.successfulAsList
添加了一个监听器,它将完成Futures.successfulAsList
返回的未来。