2016-03-01 98 views
0

我實現了一個模擬的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'中找到構造函數。未來「的參數類型:[]」

回答

0

首先是"Don't mock type you don't own!"。通過鏈接,你可能會發現幾個原因,你爲什麼不應該這樣做。

但是,如果你真的想這樣做,然後更換通過回答女巫回報模擬將創建一個新的箭扣每次:

EasyMock.expect(executorServiceMock.submit(EasyMock.<Callable<?>>capture(callableCapture))).andAnswer(() -> { 
    Future future = EasyMock.createMock(Future.class); 
    EasyMock.expect(future.get()).andAnswer(() -> callableCapture.getValue().call()).anyTimes(); 
    EasyMock.replay(future); 
    return future; 
}).anyTimes(); 

順便說一句,你不能期望PowerMock.expectNew(Future.class)因爲Future是接口,不能被創建。

0

捕獲將始終返回上次捕獲的對象。就你而言,你似乎想要同步提交和獲取。

所以,我認爲你應該做到以下幾點:

ExecutorService executorServiceMock = createMock(ExecutorService.class); 

    expect(executorServiceMock.submit(EasyMock.<Callable<?>>anyObject())) 
     .andAnswer(() -> { 
      Future future = createMock(Future.class); 
      Object value = ((Callable<?>) getCurrentArguments()[0]).call(); 
      expect(future.get()).andReturn(value); 
      replay(future); 
      return future; 
     }) 
     .anyTimes(); 

    executorServiceMock.shutdown(); 
    expectLastCall().anyTimes(); 

    replay(executorServiceMock); 

    return executorServiceMock; 
+0

在你的情況,你所期望的返回值是整數。我想返回可調用的 – Pooya

+0

中提到的相同類型,我返回了一個Integer,因爲我用Integer測試了它。它可以更通用。我相應地修改了答案。 – Henri