我一直在模拟一个函数ResultSetFuture的测试,我使用了来自Bare variables的示例(可行)来测试ResultSetFuture,但我正在测试/模拟的代码使用Futures#successfulAsList
,如图所示{{ 3}}。因此,在第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
答案 0 :(得分:0)
您需要在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
答案 1 :(得分:0)
您必须模拟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
返回的未来。