CompletableFuture usability and unit test












6















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



Fist of all, what do you think about this lines of code? I need to send request to different services 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 mocking 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!










share|improve this question





























    6















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



    Fist of all, what do you think about this lines of code? I need to send request to different services 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 mocking 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!










    share|improve this question



























      6












      6








      6


      1






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



      Fist of all, what do you think about this lines of code? I need to send request to different services 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 mocking 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!










      share|improve this question
















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



      Fist of all, what do you think about this lines of code? I need to send request to different services 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 mocking 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!







      java unit-testing testing junit mockito






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 25 '17 at 19:56









      Arghavan

      1,0461612




      1,0461612










      asked Jan 25 '17 at 18:25









      LeoLeo

      4517




      4517
























          2 Answers
          2






          active

          oldest

          votes


















          6














          If I were you, I would simply mock the services A and B and your executors, then inject them thanks to the annotation @InjectMocks as they are fields of your class.



          If you want mock the method execute of your Executor, you should rather proceed as next to simply call the method run of the provided Runnable:



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


          So basically your test would be something like this:



          @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());
          }
          }





          share|improve this answer


























          • Doing this I get NPE because I have to mock my ExecutorService (I'm using a custom one) but if I use a moked one, the test never ends. Of course if I use the default executor service, without sending mine to CompletableFuture.supplyAsync(), it works like a charm .

            – Leo
            Jan 25 '17 at 19:52








          • 1





            Response updated, please check again

            – Nicolas Filotto
            Jan 25 '17 at 20:24






          • 1





            YES! thank you! that's what I have to do always I want to mock the ExecutionService.execute() method? It is exactly what I was trying to do but in a way it works.

            – Leo
            Jan 25 '17 at 20:34



















          1














            @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);
          }
          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41858894%2fcompletablefuture-usability-and-unit-test%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            6














            If I were you, I would simply mock the services A and B and your executors, then inject them thanks to the annotation @InjectMocks as they are fields of your class.



            If you want mock the method execute of your Executor, you should rather proceed as next to simply call the method run of the provided Runnable:



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


            So basically your test would be something like this:



            @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());
            }
            }





            share|improve this answer


























            • Doing this I get NPE because I have to mock my ExecutorService (I'm using a custom one) but if I use a moked one, the test never ends. Of course if I use the default executor service, without sending mine to CompletableFuture.supplyAsync(), it works like a charm .

              – Leo
              Jan 25 '17 at 19:52








            • 1





              Response updated, please check again

              – Nicolas Filotto
              Jan 25 '17 at 20:24






            • 1





              YES! thank you! that's what I have to do always I want to mock the ExecutionService.execute() method? It is exactly what I was trying to do but in a way it works.

              – Leo
              Jan 25 '17 at 20:34
















            6














            If I were you, I would simply mock the services A and B and your executors, then inject them thanks to the annotation @InjectMocks as they are fields of your class.



            If you want mock the method execute of your Executor, you should rather proceed as next to simply call the method run of the provided Runnable:



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


            So basically your test would be something like this:



            @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());
            }
            }





            share|improve this answer


























            • Doing this I get NPE because I have to mock my ExecutorService (I'm using a custom one) but if I use a moked one, the test never ends. Of course if I use the default executor service, without sending mine to CompletableFuture.supplyAsync(), it works like a charm .

              – Leo
              Jan 25 '17 at 19:52








            • 1





              Response updated, please check again

              – Nicolas Filotto
              Jan 25 '17 at 20:24






            • 1





              YES! thank you! that's what I have to do always I want to mock the ExecutionService.execute() method? It is exactly what I was trying to do but in a way it works.

              – Leo
              Jan 25 '17 at 20:34














            6












            6








            6







            If I were you, I would simply mock the services A and B and your executors, then inject them thanks to the annotation @InjectMocks as they are fields of your class.



            If you want mock the method execute of your Executor, you should rather proceed as next to simply call the method run of the provided Runnable:



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


            So basically your test would be something like this:



            @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());
            }
            }





            share|improve this answer















            If I were you, I would simply mock the services A and B and your executors, then inject them thanks to the annotation @InjectMocks as they are fields of your class.



            If you want mock the method execute of your Executor, you should rather proceed as next to simply call the method run of the provided Runnable:



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


            So basically your test would be something like this:



            @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());
            }
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 25 '17 at 20:43

























            answered Jan 25 '17 at 19:24









            Nicolas FilottoNicolas Filotto

            32.9k94973




            32.9k94973













            • Doing this I get NPE because I have to mock my ExecutorService (I'm using a custom one) but if I use a moked one, the test never ends. Of course if I use the default executor service, without sending mine to CompletableFuture.supplyAsync(), it works like a charm .

              – Leo
              Jan 25 '17 at 19:52








            • 1





              Response updated, please check again

              – Nicolas Filotto
              Jan 25 '17 at 20:24






            • 1





              YES! thank you! that's what I have to do always I want to mock the ExecutionService.execute() method? It is exactly what I was trying to do but in a way it works.

              – Leo
              Jan 25 '17 at 20:34



















            • Doing this I get NPE because I have to mock my ExecutorService (I'm using a custom one) but if I use a moked one, the test never ends. Of course if I use the default executor service, without sending mine to CompletableFuture.supplyAsync(), it works like a charm .

              – Leo
              Jan 25 '17 at 19:52








            • 1





              Response updated, please check again

              – Nicolas Filotto
              Jan 25 '17 at 20:24






            • 1





              YES! thank you! that's what I have to do always I want to mock the ExecutionService.execute() method? It is exactly what I was trying to do but in a way it works.

              – Leo
              Jan 25 '17 at 20:34

















            Doing this I get NPE because I have to mock my ExecutorService (I'm using a custom one) but if I use a moked one, the test never ends. Of course if I use the default executor service, without sending mine to CompletableFuture.supplyAsync(), it works like a charm .

            – Leo
            Jan 25 '17 at 19:52







            Doing this I get NPE because I have to mock my ExecutorService (I'm using a custom one) but if I use a moked one, the test never ends. Of course if I use the default executor service, without sending mine to CompletableFuture.supplyAsync(), it works like a charm .

            – Leo
            Jan 25 '17 at 19:52






            1




            1





            Response updated, please check again

            – Nicolas Filotto
            Jan 25 '17 at 20:24





            Response updated, please check again

            – Nicolas Filotto
            Jan 25 '17 at 20:24




            1




            1





            YES! thank you! that's what I have to do always I want to mock the ExecutionService.execute() method? It is exactly what I was trying to do but in a way it works.

            – Leo
            Jan 25 '17 at 20:34





            YES! thank you! that's what I have to do always I want to mock the ExecutionService.execute() method? It is exactly what I was trying to do but in a way it works.

            – Leo
            Jan 25 '17 at 20:34













            1














              @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);
            }
            }





            share|improve this answer




























              1














                @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);
              }
              }





              share|improve this answer


























                1












                1








                1







                  @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);
                }
                }





                share|improve this answer













                  @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);
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 25 '18 at 17:27









                Roshan OswalRoshan Oswal

                111




                111






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41858894%2fcompletablefuture-usability-and-unit-test%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Lallio

                    Unable to find Lightning Node

                    Futebolista