在Net中模拟弹性搜索响应 [英] Mock Elastic Search response in.Net

查看:133
本文介绍了在Net中模拟弹性搜索响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Elastic Search Nest库代码,需要模拟我从弹性搜索索引中得到的响应。

I have Elastic Search Nest library code and need to mock the response i am getting from elastic search index.

var obj = service.Search<TestDocument>(new student().Query());
var Name= obj.Aggs.Terms("Name");

用于测试:
我正在快速查看但遇到问题后创建Nest对象- 集合-是内部受保护的财产,我无法设置此值。

For Testing : I am creating the Nest object after doing quick watch but facing issue -Aggregations - is a internal protected property and i am not able to set this value.

                           new Nest.KeyedBucket<object>
                           {   
                               Key="XYZ school",
                               KeyAsString=null,
                               Aggregations=new Dictionary<string, IAggregationContainer>{}
                           }

请提出解决方案或我可以用来模拟弹性搜索嵌套对象的任何其他方法。

Please suggest solution or any other approach i can use to mock elastic search nest object .

推荐答案

如果您真的想保留来自客户端的响应,则可以使用Moq进行以下操作

If you really want to stub the response from the client, you could do something like the following with Moq

var client = new Mock<IElasticClient>();

var searchResponse = new Mock<ISearchResponse<object>>();

var aggregations = new AggregateDictionary(new Dictionary<string, IAggregate> {
    ["Name"] = new BucketAggregate
    {
        Items = new List<KeyedBucket<object>>
        {
            new Nest.KeyedBucket<object>(new Dictionary<string, IAggregate>())
            {
                Key = "XYZ school",
                KeyAsString = null,
                DocCount = 5
            }
        }.AsReadOnly()
    }
});

searchResponse.Setup(s => s.Aggregations).Returns(aggregations);

client.Setup(c => c.Search<object>(It.IsAny<Func<SearchDescriptor<object>, ISearchRequest>>()))
    .Returns(searchResponse.Object);

var response = client.Object.Search<object>(s => s);

var terms = response.Aggregations.Terms("Name");

另一种方法是使用 InMemoryConnection 并返回已知的JSON

Another way would be to use the InMemoryConnection and return known JSON in response to a request..

不过,出于测试目的,最好运行一个Elasticsearch实例并对其进行集成测试。看看 Elastic.Xunit ,它提供了一种启动Elasticsearch集群的简便方法用于测试目的。客户端在集成测试中使用它。

For testing purposes however, it may be better to have an instance of Elasticsearch running, and perform integration tests against it. Take a look at Elastic.Xunit which provides an easy way to spin up an Elasticsearch cluster for testing purposes. This is used by the client in integration tests.

您可以从 Appveyor供稿

这篇关于在Net中模拟弹性搜索响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆