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")
@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.
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.
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.
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")));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With