1

I have tried to mock the response for the below method, but it's not working. Not able to mock the search.hits().hits() method.

Any idea how to do that?

SearchResponse<Product> search = client.search(s -> s
    .index("products")
    .query(q -> q
        .term(t -> t
            .field("name")
            .value(v -> v.stringValue("bicycle"))
        )),
    Product.class);

for (Hit<Product> hit: search.hits().hits()) {
    processProduct(hit.source());
}

Reference for code- https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/connecting.html#_your_first_request

Ashish Mishra
  • 145
  • 3
  • 13
  • let me guess: You tried to mock a "chained call" like: `when(someMock.hits().hits()).then...`? No, though this is legal syntax&runtime, it won't give you the desired result, you have to : `when(someMock.hits()).then...` pass some (real or mock) object/class... and when this is again a mock, you have to `when(someOtherMock.hits()).then...` – xerx593 Sep 27 '22 at 18:19
  • Hit hit = mock(Hit.class); HitsMetadata hitsMetadata = mock(HitsMetadata.class); when(searchResponse.hits()).thenReturn(hitsMetadata); when(hit.source()).thenReturn(mockContent(Collections.singletonList("ScaledImage"),1)); when(hitsMetadata.hits()).thenReturn(List.of(hit)); Mockito.when(elasticClient.search((SearchRequest) Mockito.any(), Mockito.any())) .thenReturn(searchResponse); – Ashish Mishra Sep 28 '22 at 02:21
  • i tried this but its not working – Ashish Mishra Sep 28 '22 at 02:22
  • Can you check [this](https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/test/java/co/elastic/clients/documentation/usage/SearchingTest.java) code. it might help you to writing junit. – Sagar Patel Sep 28 '22 at 08:33

0 Answers0