1

I am writing some tests for a system that reads from ES using ElasticSearch.NET. The program transforms a search result into a different format.

What I would like to do in the test is use a large JSON file as a mock response from ES, in order to test that the transformer works.

However, I need to create a valid ISearchResponse instance for the transformer, and the only way I have found to mock the result is to manually create each object in the hierarchy, for example:

var aggregations = new AggregateDictionary(new Dictionary<string, IAggregate>
{
    ["my_aggregate"] = new BucketAggregate
    {
        Items = new List<IBucket>()
        {
            new DateHistogramBucket(new Dictionary<string, IAggregate>()
            {
                {
                    "key", new KeyedValueAggregate(){Value = 10, ValueAsString = "10"}
                }
            })
        }.AsReadOnly()
    }
});
searchResponse.Aggregations.Returns(info => new AggregateDictionary(aggregations));

However, I'd like to mock a much bigger response object, and not have to deal with precisely modeling it, as that could lead to unforeseen issues.

Is there some kind of serializer that I can use to convert a JSON object into an ElasticSearch.NET search response object, or even a single aggregation dictionary?

Ynhockey
  • 3,845
  • 5
  • 33
  • 51

1 Answers1

0

Looks like it's possible by mocking the connection and client together, here is an example:

jsonObjectAsString is the mock JSON in string format.

var responseBytes = Encoding.UTF8.GetBytes(jsonObjectAsString);
var connection = new InMemoryConnection(responseBytes, 200); 
var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(connectionPool, connection).DefaultIndex("my_aggregate");
var client = new ElasticClient(settings);
var searchResponse = client.Search<WebhookTotalTimeRecord>();

The searchResponse will be a valid ISearchResponse object with the correct data.

Ynhockey
  • 3,845
  • 5
  • 33
  • 51