.Net

时间:2018-10-24 13:01:37

标签: elasticsearch nest elastic-stack elasticsearch-5

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

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

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

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

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

1 个答案:

答案 0 :(得分:2)

如果您真的想要保留来自客户端的响应,则可以使用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 and return known JSON in response to a request.

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

您可以从the MyGet feed获得Elastic.Xunit。