2017-04-12 26 views
0

は、私はこのような呼び出し可能を実行するために一緒に働く2つのクラスを持っていると仮定します。mockitoで非同期呼び出しをスタブする方法は?

public class blah { 

@Autowired 
private ExecutorServiceUtil executorServiceUtil; 

@Autowired 
private RestTemplate restClient; 

public SomeReturnType getDepositTransactions(HttpHeaders httpHeaders) { 

    ExecutorService executor = executorServiceUtil.createExecuter(); 
    try { 
     DepositTransactionsAsyncResponse asyncResponse = getPersonalCollectionAsyncResponse(httpHeaders, executor); 
     // do some processing 
     // return appropriate return type 
    }finally { 
     executorServiceUtil.shutDownExecutor(executor); 
    } 
} 

Future<ResponseEntity<PersonalCollectionResponse>> getPersonalCollectionAsyncResponse(HttpHeaders httpHeaders, ExecutorService executor) { 

    PersonalCollectionRequest personalCollectionRequest = getpersonalCollectionRequest(); // getPersonalCollectionRequest populates the request appropriately 
    return executor.submit(() -> restClient.exchange(personalCollectionRequest, httpHeaders, PersonalCollectionResponse.class)); 
    } 
} 

public class ExecutorServiceUtil { 

    private static Logger log = LoggerFactory.getLogger(ExecutorServiceUtil.class); 

    public ExecutorService createExecuter() { 
     return Executors.newCachedThreadPool(); 
    } 

    public void shutDownExecutor(ExecutorService executor) { 
      try { 
       executor.shutdown(); 
       executor.awaitTermination(5, TimeUnit.SECONDS); 
      } 
      catch (InterruptedException e) { 
       log.error("Tasks were interrupted"); 
      } 
      finally { 
       if (!executor.isTerminated()) { 
        log.error("Cancel non-finished tasks"); 
       } 
       executor.shutdownNow(); 
      } 
     } 

} 

はどのような応答をスタブと、すぐにそれを返すためにMockitoを使用することができますか?

私はないによってテストコードであなたのExecutorServiceUtilを使用していることをあなたは以下試みたが、私のinnovcation.args()が復帰[ヌル]

PowerMockito.when(executor.submit(Matchers.<Callable<ResponseEntity<OrxPendingPostedTrxCollectionResponseV3>>> any())).thenAnswer(new Answer<FutureTask<ResponseEntity<OrxPendingPostedTrxCollectionResponseV3>>>() { 

      @Override 
      public FutureTask<ResponseEntity<OrxPendingPostedTrxCollectionResponseV3>> answer(InvocationOnMock invocation) throws Throwable { 
       Object [] args = invocation.getArguments(); 
       Callable<ResponseEntity<OrxPendingPostedTrxCollectionResponseV3>> callable = (Callable<ResponseEntity<OrxPendingPostedTrxCollectionResponseV3>>) args[0]; 
       callable.call(); 
         return null; 
        } 
       }); 
+0

@ GhostCatの提案では、呼び出しを同期的に返すことができ、応答ロジックを削除することができました。 – Norbert

答えて

1

てきました。私が意味するところは:あなたはモックのutilクラスをプロダクションコードに提供しています!

モックは「同じスレッド実行者サービス」を返します。 「実サービス」(スレッドプールに基づく)の代わりに使用されます。そのような同じスレッド・エグゼキュータを書くことは、実際にはまっすぐです - hereを参照してください。言い換えれば

:あなたがここに2つの異なるユニットテストしたい:あなたが単独であなたのExecutorServiceUtilクラスのユニットテストを書く

  1. を。
  2. blahクラスの単体テストを書いています...模擬サービスを使用しています(これは実際には実行されていません) 。そして、突然、「それは非同期」の周りのあなたのすべての問題はなくなります。なぜなら、「非同期」部分は薄い空気中で消滅するからです。
関連する問題