我實現了一個模擬的ExecutorService,而不需要創建線程立即返回結果:嘲笑的ExecutorService總是返回相同的嘲笑未來
public static ExecutorService createMock() throws Exception {
ExecutorService executorServiceMock = EasyMock.createMock(ExecutorService.class);
Future future = EasyMock.createMock(Future.class);
Capture<Callable<?>> callableCapture = new Capture<>();
EasyMock.expect(executorServiceMock.submit(EasyMock.<Callable<?>>capture(callableCapture))).andReturn(future).anyTimes();
EasyMock.expect(future.get()).andAnswer(() -> callableCapture.getValue().call()).anyTimes();
executorServiceMock.shutdown();
EasyMock.expectLastCall().anyTimes();
EasyMock.replay(future, executorServiceMock);
return executorServiceMock;
}
的問題是,它總是返回相同的[嘲笑] Future對象。我需要基於傳遞給executorServiceMock.submit()的可調用對象返回未來模擬的新實例() 我試圖使用PowerMock.expectNew(Future.class),但它抱怨「沒有在類'java.util.concurrent'中找到構造函數。未來「的參數類型:[]」
在你的情況,你所期望的返回值是整數。我想返回可調用的 – Pooya
中提到的相同類型,我返回了一個Integer,因爲我用Integer測試了它。它可以更通用。我相應地修改了答案。 – Henri