Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock external dependency that returns a Future of list

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")
like image 528
user304611 Avatar asked Jul 28 '17 20:07

user304611


People also ask

What is difference between @mock and @injectmock?

@InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock annotations into this instance. @Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class.

How do you mock method which returns void?

Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.

Can we mock interface using Mockito?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called.


2 Answers

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")));
like image 163
Todd Avatar answered Oct 02 '22 11:10

Todd


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);
like image 27
Dmytro Maslenko Avatar answered Oct 02 '22 13:10

Dmytro Maslenko