0

I have following piece of Elasticsearch code

SearchRequestBuilder builder = client.prepareSearch(indexRange).setTypes(module).setSize(json.getPageSize())
    .setFrom(json.getOffset()).setFetchSource(prepareFieldListToLoad(), prepareFieldListToIgnore())
    .setExplain(false);

How can i mock it for junit testing using mockito?

Manish Kumar
  • 10,214
  • 25
  • 77
  • 147
  • Possible duplicate of https://stackoverflow.com/questions/8501920/how-to-mock-a-builder-with-mockito – Shawn Sep 09 '20 at 22:09

1 Answers1

0

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:

Shawn
  • 8,374
  • 5
  • 37
  • 60