15

I have a class which have external dependency that returns future of lists. How to mock the external dependency?

 public void meth() {
     //some stuff
     Future<List<String>> f1 = obj.methNew("anyString")
     //some stuff
 }

 when(obj.methNew(anyString()).thenReturn("how to intialise some data here, like list of names")
user304611
  • 297
  • 1
  • 4
  • 14

2 Answers2

25

You can create the future and return it using thenReturn(). In the case below, I create an already completed Future<List<String>> using CompletableFuture.

when(f1.methNew(anyString()))
        .thenReturn(CompletableFuture.completedFuture(Arrays.asList("A", "B", "C")));
Todd
  • 30,472
  • 11
  • 81
  • 89
12

As alternative way you may mock the Future as well. The benefit of such way is ability to define any behavior.

For example you want to test a case when a task was canceled:

final Future<List<String>> mockedFuture = Mockito.mock(Future.class);
when(mockedFuture.isCancelled()).thenReturn(Boolean.TRUE);
when(mockedFuture.get()).thenReturn(asList("A", "B", "C"));

when(obj.methNew(anyString()).thenReturn(mockedFuture);
Dmytro Maslenko
  • 2,247
  • 9
  • 16