mercredi 25 janvier 2017

CompletableFuture usability and unit test

I'm learning about java 8 CompletableFuture and ended up with this.

Fist of all, what do you thing about this lines of code? I need to send request to different service in parallel and then wait for all of them to response and continue working.

//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();

And even the code is doing what I want, I'm having problems testing the class where that code is. I tried using Mockito and do something like:

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

Where executor services and services responses are mocks but the test never ends and the thread keeps waiting for something in this line

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

Any hint on what I'm missing here? Thank you!

Aucun commentaire:

Enregistrer un commentaire