首页 > 解决方案 > 如何模拟 Elasticsearch .Net 客户端?

问题描述

我正在使用 Elasticsearch .Net Client 6.x,我有一些代码,例如:

if(this.elasticClient.IndexExists("indexName").Exists){
    // do something
}

this.elasticClient.CreateIndex(
    newIndex,
    x => x.Settings(s => s.NumberOfShards(1)).Mappings(ms => ms.Map<T>(m => m.AutoMap())));

var searchResponse = client.Search<dynamic>(
    s => s.AllTypes()
        .Index(
            new[] { "indexName1", "indexName"}).IgnoreUnavailable().Size(size).From(from).Query(
            q => q.Bool(b => b.Must(m => m.SimpleQueryString(c => c.Query(query).Lenient().AnalyzeWildcard())))));

现在在我的单元测试中,我想测试descriptor传递给每个方法的确切内容,我该怎么做?

var existsResponse = new Mock<ExistsResponse>();
existsResponse.Setup(x => x.Exists).Returns(false);  // Oops: can't do this since Exists is not virtual, abstract
this.elasticClient.Setup(x => x.IndexExists("indexName", null)).Returns(existsResponse.Object);

this.elasticClient.Verify(
    x => x.CreateIndex("IndexName", It.Is<Func<CreateIndexDescriptor, ICreateIndexRequest>>(x => /*what goes here??*/)),
    Times.Once);

this.elasticClient.Verify(
    x => x.Search<dynamic>(It.Is<Func<SearchDescriptor<dynamic>>>(x => /*what goes here??*/)),
    Times.Once);

我是否应该简单地将 elasticClient 包装在一个类中并实现我使用的每个方法,并将其作为依赖注入传递?

标签: c#unit-testingelasticsearchmockingnest

解决方案


推荐阅读