2

I have a method called doParallelThings:

public Dummy doParallelThings(Map<String, String> mapp) throws Exception {
        Dummy dummy = new Dummy();

        CompletableFuture<Ans1> one = firstService.getOne(mapp.get("some1"), mapp);
        CompletableFuture<Ans2> two = secondService.getTwo(headersMap.get("some2"), mapp);

        CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(one, two);
        try {
            combinedFuture.get();
            dummy.setOne(one.get());
            dummy.setTwp(two.get());

        } catch (Throwable e) {

        }
        return dummy;
    }

Code works fine but when I'm trying to test it, combinedFuture.get(); goes to infinite loop.

Unit test is as below:

@Mock
    private CompletableFuture<Void> ans;

@Test
    public void testDoParallelThings() throws Exception {

        PowerMockito.mockStatic(CompletableFuture.class);
        PowerMockito.when(CompletableFuture.allOf(any())).thenReturn(ans);
        when(ans.get()).thenReturn(null);

        Dummy dummy = dummyService. doParallelThings(mockMap);
        assertNotNull(dummy);
    }

I have also added @RunWith(PowerMockRunner.class) @PrepareForTest({CompletableFuture.class}) above the test class.

What am I missing?

Harshini
  • 459
  • 1
  • 7
  • 23
  • You should mock `firstService.getOne` and `secondService.getTwo` instead, so they return a already completed future. – Johannes Kuhn Sep 24 '19 at 04:42
  • I tried that as well, ```@Mock private CompletableFuture mockOneFuture; @Mock private One mockOne; when(firstService.getOne(any(), any())).thenReturn(mockOneFuture); mockOneFuture.complete(mockOne);``` – Harshini Sep 24 '19 at 04:50
  • As your method (`CompletableFuture.allOf`) has a varargs parameter, you need to mock it arcordingly. Check this [`answer`](https://stackoverflow.com/a/2634588/11514534). – second Sep 24 '19 at 14:15

1 Answers1

3

when(firstService.getOne(any(), any())).thenReturn(CompletableFuture.completedFuture(mockOne));

solved my problem

Harshini
  • 459
  • 1
  • 7
  • 23
  • 1
    So instead of mocking the static method `CompletableFuture.allOf` you changed your test to use real `CompletableFutures` instead and mocked the first and second service instead. That is probably the btter choice for a simple unit test. – second Sep 24 '19 at 14:19
  • Have almost exactly the same code but the moment I add CompletableFuture.completedFuture in the below line of code it gives me below error. Doesn't come when I remove it but then my Future is incomplete & in loop. Is it possible to share ur code so that I can check if I'm missing something? when(firstService.getOne(any(),any())).thenReturn(CompletableFuture.completedFuture(mockOne)); org.mockito.exceptions.misusing.UnfinishedStubbingException: Unfinished stubbing detected here: -> at com.myCompany.TestClass.testMethodNotNull(TestClass.java:52) E.g. thenReturn() may be missing – Jaison Varghese Apr 08 '20 at 18:22