基于guava-libraries example,我正在使用ListenableFuture。
我正在使用:
java 1.6
JDeveloper 11.1.1.6.0
番石榴13.0.1.jar
的junit-4.5.jar
EasyMock的-3.1.jar
powermock-EasyMock的-1.4.12-full.jar
我正在尝试确保在异步模式下调用被测方法。
我的Manager.java代码是:
...
public synchronized void refreshAsync(final String id) {
m_Log.entry(id);
ListeningExecutorService service =
MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
ListenableFuture<Details> getDetailsTask =
service.submit(new Callable<Details>() {
@Override
public Details call() {
System.out.println(Thread.currentThread().toString());
return MyCacheManager.getDetails(id);
}
});
Futures.addCallback(getDetailsTask ,
new FutureCallback<Details>() {
// we want this handler to run immediately after we push the big red button!
public void onSuccess(Details details) {
System.out.println("Success");
//TODO: publish event
}
public void onFailure(Throwable thrown) {
System.out.println("Failed");
//TODO: log
}
});
service.shutdown();
m_Log.exit("done async");
}
...
我的测试是:
@RunWith(PowerMockRunner.class)
@PrepareForTest( { Manager.class, MyCacheManager.class, TWResourceManager.class, Logger.class })
public class DetailsTests {
{
...
@Test (timeout = 4000)
public void refreshAsync_RequestedInAsyncMode_NoWaitForComplete() throws Exception {
// Creating nice mock - because we are not caring about methods call order
mockStatic(MyCacheManager.class);
// Setup
final int operationTimeMilis = 5000;
expect(MyCacheManager.getDetails(anyObject(String.class))).andStubAnswer(new IAnswer<Details>() {
public Details answer() {
try {
System.out.println("start waiting 5 sec");
System.out.println(Thread.currentThread().toString());
Thread.sleep(operationTimeMilis);
System.out.println("finished waiting 5 sec");
} catch (InterruptedException e) {
e.printStackTrace();
}
return Details.getEmpty();
}
});
replay(MyCacheManager.class);
replayAll();
ISchemaActionsContract controller = new TWManager();
controller.refreshSchemaDetailsAsync("schema_id");
// We need not to verify mocks, since all we are testing is timeout
// verifyAll();
}
}
当我运行/调试测试时 - 它在超时时总是失败。似乎在“同步”模式下调用模拟方法“MyCacheManager.getDetails”。
但是当我从常规代码/调试调用相同的函数时 - 它以异步模式运行(我将Thread.sleep(10000)放入MyCacheManager.getDetails方法,并且退出Manager.refreshAsync方法而不等待/被阻止。
此外,如果我要更改方法以使用常规FutureTask,请按预期测试传递。
...
Object res = null;
FutureTask task = new FutureTask(new Runnable() {
@Override
public void run() {
MyCacheManager.getDetails(id);
}
}, res);
m_Log.debug("async mode - send request and do not wait for answer.");
Executors.newCachedThreadPool().submit(task);
任何想法都会受到欢迎! :)
谢谢!