如何模拟IElasticClient Get方法?

时间:2016-01-18 11:19:12

标签: c# unit-testing elasticsearch moq nest

这是我班级的最小代表,通过Nest 1.7处理与Elasticsearch的沟通:

public class PeopleRepository
{
    private IElasticClient client;

    public PeopleRepository(IElasticClient client)
    {
        this.client = client;
    }

    public Person Get(string id)
    {
        var getResponse = client.Get<Person>(p => p.Id(id));

        // Want to test-drive this change:
        if (getResponse.Source == null) throw new Exception("Person was not found for id: " + id);

        return getResponse.Source;
    }
}

正如代码中所述,我试图试驾一定的变化。我使用NUnit 2.6.4和Moq 4.2尝试以下列方式执行此操作:

[Test]
public void RetrieveProduct_WhenDocNotFoundInElastic_ThrowsException()
{
    var clientMock = new Mock<IElasticClient>();
    var getSelectorMock = It.IsAny<Func<GetDescriptor<Person>, GetDescriptor<Person>>>();
    var getRetvalMock = new Mock<IGetResponse<Person>>();

    getRetvalMock
        .Setup(r => r.Source)
        .Returns((Person)null);

    clientMock
        .Setup(c => c.Get<Person>(getSelectorMock))
        .Returns(getRetvalMock.Object);

    var repo = new PeopleRepository(clientMock.Object);

    Assert.Throws<Exception>(() => repo.Get("invalid-id"));
}

但是,我错误地嘲笑了各种ElasticClient位:Get上的IElasticClient方法返回null,因此在我的代码抛出之前在getResponse.Source上导致NullReferenceException我希望它抛出异常。

如何正确模仿Get<T>上的IElasticClient方法?

1 个答案:

答案 0 :(得分:4)

您不能在It.IsAny调用之外使用Setup方法,否则会将其视为null。将It.IsAny移动到设置中应该有效:

 clientMock
        .Setup(c => c.Get<Person>(It.IsAny<Func<GetDescriptor<Person>, GetDescriptor<Person>>>()))
        .Returns(getRetvalMock.Object);