web-dev-qa-db-ja.com

CompletableFutureの使いやすさと単体テスト

Java 8 CompletableFutureについて学んでいるが、これで終わった。

まず、このコード行についてどう思いますか?リクエストを異なるサービスに並行して送信し、それらすべてが応答するのを待って作業を続ける必要があります。

//service A
CompletableFuture<ServiceAResponse> serviceAFuture = CompletableFuture.supplyAsync(
    () -> this.ServiceA.retrieve(serviceARequest), serviceAExecutorService
);

//service B
CompletableFuture<ServiceBResponse> serviceBFuture = CompletableFuture.supplyAsync(
    () -> this.ServiceB.retrieve(serviceBRequest), serviceBExecutorService
);

CompletableFuture.allOf(serviceAFuture, serviceBFuture).join();
ServiceAResponse responseA = serviceAFuture.join();
ServiceBResponse responseB = serviceBFuture.join();

そして、コードが私が望んでいることをしていても、そのコードがあるクラスをテストするのに問題があります。私はMockitoを使用してみて、次のようなことをしました:

doAnswer(invocation -> CompletableFuture.completedFuture(this.serviceAResponse))
    .when(this.serviceAExecutorService)
    .execute(any());

エグゼキューターサービスとサービスレスポンスはモックされますが、テストは終了せず、スレッドはこの行の何かを待ち続けます

CompletableFuture.allOf(serviceAFuture, serviceBFuture).join();

ここで何が欠けているかについてのヒントはありますか?ありがとうございました!

9
Leo

もし私があなただったら、サービスAとBとあなたのエグゼキュータを単純にモックし、アノテーションのおかげでそれらを注入します @InjectMocks クラスのフィールドであるため。

executeのメソッドExecutorをモックしたい場合は、次のように提供されたrunのメソッドRunnableを単純に呼び出す必要があります。

doAnswer(
    (InvocationOnMock invocation) -> {
        ((Runnable) invocation.getArguments()[0]).run();
        return null;
    }
).when(serviceAExecutorService).execute(any(Runnable.class));

基本的に、テストは次のようになります。

@RunWith(MockitoJUnitRunner.class)
public class CompletableFutureServiceTest {

    // The mock of my service A
    @Mock
    private ServiceA ServiceA;
    // The mock of my service B
    @Mock
    private ServiceB ServiceB;
    // The mock of your executor for the service A
    @Mock
    private Executor serviceAExecutorService;
    // The mock of your executor for the service B
    @Mock
    private Executor serviceBExecutorService;
    // My class in which I want to inject the mocks
    @InjectMocks
    private CompletableFutureService service;

    @Test
    public void testSomeMethod() {
        // Mock the method execute to call the run method of the provided Runnable
        doAnswer(
            (InvocationOnMock invocation) -> {
                ((Runnable) invocation.getArguments()[0]).run();
                return null;
            }
        ).when(serviceAExecutorService).execute(any(Runnable.class));
        doAnswer(
            (InvocationOnMock invocation) -> {
                ((Runnable) invocation.getArguments()[0]).run();
                return null;
            }
        ).when(serviceBExecutorService).execute(any(Runnable.class));

        ServiceAResponse serviceAResponse = ... // The answer to return by service A
        // Make the mock of my service A return my answer
        when(ServiceA.retrieve(any(ServiceARequest.class))).thenReturn(
            serviceAResponse
        );
        ServiceBResponse serviceBResponse = ... // The answer to return by service B
        // Make the mock of my service B return my answer
        when(ServiceB.retrieve(any(ServiceBRequest.class))).thenReturn(
            serviceBResponse
        );

        // Execute my method
        ServiceResponse response = service.someMethod(
            new ServiceARequest(), new ServiceBRequest()
        );

        // Test the result assuming that both responses are wrapped into a POJO
        Assert.assertEquals(serviceAResponse, response.getServiceAResponse());
        Assert.assertEquals(serviceBResponse, response.getServiceBResponse());
    }
}
11
Nicolas Filotto
  @Mock
  private AsyncExecuter asyncExecuter;
  @Mock
  private CompletableFuture<XyzSample> xyzSampleResponse;
  @Mock
  private CompletableFuture<Map<String, String>> abcSampleResponse;

 @Before
  public void setUp() throws Exception {

    abcSampleResponse = CompletableFuture.completedFuture(TestUtil.readJsonResource(
        "misc_mapper_response.json", new TypeReference<Map<String, String>>() {
        }));

    xyzSampleResponse = CompletableFuture.completedFuture(TestUtil.readJsonResource(
        "gp_facade_response.json", new TypeReference<XyzSample>() {
        }));

  }

   @Test
  public void testAbcMethod() {

    Mockito.doReturn(abcSampleResponse).when(asyncExecuter)
        .callPgEndpoint(TestConstants.TEST_CUSTOMER_ID);

    Mockito.doReturn(xyzSampleResponse).when(asyncExecuter)
        .getUserPreference(TestConstants.TEST_CUSTOMER_ID);


    final ActualResponse actualResponse = globalPositionService
        .getGlobalPosition(TestConstants.TEST_CUSTOMER_ID);

    assertNotNull(actualResponse);
}

=====Service
public ActualResponse getGlobalPosition(final String customerId) {

    final CompletableFuture<Map<String, String>> abcSampleResponse = asyncExecuter
        .getProductTypeInfo();
    final CompletableFuture<XyzSample> xyzSampleResponse = asyncExecuter
        .getUserPreference(customerId);

    try {
      return new ResponseDecorator(pgResponse.get(), userPreferenceResponse.get(),
          productTypeInfo.get()).decorate();
    } catch (final Exception e) {
      log.error("Error Occurred while building the response", e);
    }
    return null;
  }

@Component
public class AsyncExecuter {
  public CompletableFuture<XyzSample> callPgEndpoint(final String customerId) {
    return CompletableFuture.completedFuture(xxx);
  }
}
2
Roshan Oswal