Mocking Search Results in new Java API

The example above did not completely work because a call to .source() always returned null. You have to define the .source() structure also:

    SearchResponse<ESMetrics> createMockedResponse(long value) {

        ESMetrics entry = new ESMetrics("aln-nbadev4.labs.server.com",
                NAME_FIELD_VALUE, SOURCE_FIELD_VALUE);
        entry.setValue(value);

        return SearchResponse.of(r -> r
                .took(0)
                .timedOut(false)
                .hits(h -> h
                        .total(t -> t.value(1).relation(TotalHitsRelation.Eq))
                        .hits(hit -> hit
                                .id("1234")
                                .index("metrics-7.17.9-2023.07.06")
                                .fields(Map.of("hostname", JsonData.of("aln-nbadev4.labs.server.com"),
                                        "@timestamp", JsonData.of("2020-09-17T20:23:55.382Z"),
                                         NAME_FIELD_NAME, JsonData.of(NAME_FIELD_VALUE),
                                        SOURCE_FIELD_NAME, JsonData.of(SOURCE_FIELD_VALUE),
                                        VALUE_FIELD, JsonData.of(value)))
                                .source(entry))
                )
                .shards(s -> s
                        .total(1)
                        .failed(0)
                        .successful(1)
                )
        );
    }

Then you can mock it like so:

        SearchResponse<ESMetrics> searchResponse = createMockedResponse(1);
        ElasticsearchClient client = mock(ElasticsearchClient.class);
        when(client.search((Function<Builder, ObjectBuilder<SearchRequest>>) any(), any())).thenReturn((SearchResponse) searchResponse);

It is also very important when defining your class that holds the Elasticsearch data that you are reading that if you are using Lombock notations you must use @NoArgsConstructor if any constructors are defined:

    @Data
    @RequiredArgsConstructor
    @NoArgsConstructor(force=true)
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class ESMetrics {