使用C#Moq模拟ElasticSearch客户端

Gia*_*ini 7 c# testing unit-testing moq elasticsearch

我正在测试我的类ElasticUtility,它需要一个实例ElasticClient才能正常工作所以我嘲笑这个类并将其注入ElasticUtility实例(utility)

    private ElasticUtility utility;
    private Mock<IElasticClient> elasticClientMock;
    private string elasticSearchIndexName;

    elasticClientMock = new Mock<IElasticClient>();
    utility = new UhhElasticUtility(elasticClientMock.Object);
Run Code Online (Sandbox Code Playgroud)

这是实际的测试代码:

[Test]
public void GetGetPvDataClientReturnNull()
{
    // arrange
    var groupId = "groupid";
    var startTime = new DateTime(2015, 08, 17, 13, 30, 00);
    var endTime = new DateTime(2015, 08, 17, 13, 40, 00);

    // act
    utility.GetPvData(groupId, startTime, endTime);

    // assert
    elasticClientMock.Verify(ec => ec.Search<SegmentRecord>(It.IsAny<Nest.ISearchRequest>()), Times.Once());
}
Run Code Online (Sandbox Code Playgroud)

当Moq库调用.Search()mocked中的方法时,我得到一个Null引用异常ElastiClient.

编辑:

构造函数ElasticUtility:

    protected ElasticUtility(IElasticClient elasticClient, string elasticIndexName)
    {
        this.ElasticClient = elasticClient;
        this.ElasticIndexName = elasticIndexName;
    }
Run Code Online (Sandbox Code Playgroud)

编辑:( GetPvData)方法:

    public IEnumerable<dynamic> GetPvData(string groupId, DateTime startTime, DateTime endTime)
    {
        var res = ElasticClient.Search<SegmentRecord>(s => s
            .Index(ElasticIndexName)
            .Filter(f =>
                f.Term(t => t.HistoryId, groupId) &&
                f.Range(i =>
                    i.OnField(a => a.DateTime).LowerOrEquals(startTime))).SortAscending(p => p.DateTime).Size(1)).Documents.ToList();

        return res.ToArray();
    }
Run Code Online (Sandbox Code Playgroud)

解决了:

   var segResp = new SearchResponse<SegmentRecord>();
    elasticClientMock.Setup(ec => ec.Search(
        It.IsAny<Func<SearchDescriptor<SegmentRecord>,
                SearchDescriptor<SegmentRecord>>>()))
        .Returns(segResp);
Run Code Online (Sandbox Code Playgroud)

Old*_*Fox 6

NullReferenceException,因为你没有指定一个行为发生search的方法.您的search方法返回null,然后您调用.Documentnull.

指定行为的方式如下:

elasticClientMock.Setup(x => x.Search<SegmentRecord>(
                             It.IsAny</* put here the right Func */>))
        .Returns( /* put here the instance you want to return */);
Run Code Online (Sandbox Code Playgroud)

你必须用正确的类型替换我的评论.

  • 好.但不应该是.Setup()而不是.Expect()? (2认同)