简体   繁体   中英

How do i mock completable Future's supplyAsync methods response?


public class Test {
    public Obj func() {
        CompletableFuture<Obj> completableFuture = CompletableFuture.supplyAsync(new ContextSupplier<Obj> {
            public Obj onGet() {
               return otherClass.giveMeObj("X", "Y");
            }
        });
        // some business logic
        return completableFuture.get();
    }
}

class Obj {
    String s;
}

In the above snippet after submitting the task to completable future i have some non trivial business logic and then i return back the task's response, from completable future. Is there a way i can mock CompletableFuture.supplyAsync() methods response.

Just define a class let say Example

public class Example {
   CompletableFuture<Obj> func(ContextSupplier<Obj> supplier) {
       <put code from your snippet here> 
   }
}

then mock this class eg with Mockito

Example exampleMock = mock(Example.class);
when(exampleMock.func(any(Class.class))).thenReturn( <put code for your mock here> );

I am not sure whether this can help you, but you don't need to mock CompletableFuture supplyAsync() method. You just mock your Task which you are submitting to supplyAsync. Then that result can be captured by thenAccept() method.

Recently I encountered such requirement and I did it like below:

  1. Java code which I wanted to Mock:

     CompletableFuture.supplyAsync(attributeUpdateTask::call).thenAccept(result->{ String status = (String)result[0]; //result of call method, in my case it was in object[] format ............. ........... }
  2. Test case code:

     @Test public void testUploadUpdatedValueFileNOK(){ Object[] response = new Object[3]; response[0] = "KO"; when(attributeUpdateTask.call()).thenReturn(response); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM