It isn't clear from this snippet how client
gets instantiated. However that happens, you need to mock that client object. Once you have that mocked, you can set the expectations on it so that when its prepareSearch
method is invoked, it returns something--likely another mock. And then you will need to set the expectations on that other mock returned by the prepareSearch
call, and so on.
You'll end up needing many mocks due to the chaining:
- a mock for client
- a mock for the object returned by the prepareSearch call
- a mock for the object returned by the setTypes call
- a mock for the object returned by the setSize call
- a mock for the object returned by the setFrom call
- a mock for the object returned by the setFetchSource call
- a mock for the object returned by the setExplain call
You could consider using a stub for the object returned by the prepareSearch
call if those "set" methods are just simple setters. Then the test will call the real setters of the object, but it still allows you to mock out some other call on the object that is more extensive.
Or if that sounds like too much manual setup, you can use Mockito's RETURN_DEEP_STUBS:
https://www.javadoc.io/doc/org.mockito/mockito-core/2.6.9/org/mockito/Answers.html
Example of deep stubs from: https://idodevjobs.wordpress.com/2015/04/09/mockito-deep-stubs-example/
public class MockingMethodChains {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Foo foo;
@Test
public void easyWayToMockMethodChaining(){
when(foo.getBar().getName()).thenReturn("Foo Bar");
assertEquals("Foo Bar", foo.getBar().getName());
}
}
Other sources: