3

In our project I have written a small class which is designed to take the result from an ElasticSearch query containing a named aggregation and return information about each of the buckets returned in the result in a neutral format, suitable for passing on to our UI.

public class AggsToSimpleChartBasicConverter {

    private SearchResponse searchResponse;
    private String aggregationName;

    private static final Logger logger = LoggerFactory.getLogger(AggsToSimpleChartBasicConverter.class);

    public AggsToSimpleChartBasicConverter(SearchResponse searchResponse, String aggregationName) {
        this.searchResponse = searchResponse;
        this.aggregationName = aggregationName;
    }

    public void setChartData(SimpleChartData chart,
                         BucketExtractors.BucketNameExtractor keyExtractor,
                         BucketExtractors.BucketValueExtractor valueExtractor) {

        Aggregations aggregations = searchResponse.getAggregations();
        Terms termsAggregation = aggregations.get(aggregationName);
        if (termsAggregation != null) {
            for (Terms.Bucket bucket : termsAggregation.getBuckets()) {
                chart.add(keyExtractor.extractKey(bucket), Long.parseLong(valueExtractor.extractValue(bucket).toString()));
            }
        } else {
            logger.warn("Aggregation " + aggregationName + " could not be found");
        }
    }

}

I want to write a unit test for this class by calling setChartData() and performing some assertions against the object passed in, since the mechanics of it are reasonably simple. However in order to do so I need to construct an instance of org.elasticsearch.action.search.SearchResponse containing some test data, which is required by my class's constructor.

I looked at implementing a solution similar to this existing question, but the process for adding aggregation data to the result is more involved and requires the use of private internal classes which would likely change in a future version, even if I could get it to work initially.

I reviewed the ElasticSearch docs on unit testing and there is a mention of a class org.elasticsearch.test.ESTestCase.java (source) but there is no guidance on how to use this class and I'm not convinced it is intended for this scenario.

How can I easily unit test this class in a manner which is not likely to break in future ES releases?

Note, I do not want to have to start up an instance of ElasticSearch, embedded or otherwise since that is overkill for this simple unit test and would significantly slow down the execution.

Community
  • 1
  • 1
Will Abson
  • 1,562
  • 7
  • 13
  • Try this approach: https://stackoverflow.com/questions/49798654/json-string-to-elasticsearch-searchresponse-with-aggregation/57117845#57117845 – technocrat Jul 19 '19 at 18:31

0 Answers0