如何模拟IElasticClient的Get方法?

Jer*_*oen 0 c# unit-testing moq elasticsearch 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如代码中所述,我正在尝试测试某些更改。我正在以以下方式使用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"));
}
Run Code Online (Sandbox Code Playgroud)

但是,我错误地嘲笑了各个ElasticClient位:Geton 的方法IElasticClient返回null,从而getResponse.Source在我的代码引发我希望其引发的异常之前导致NullReferenceException 。

如何正确模拟Get<T>方法IElasticClient

Tom*_*ode 5

您不能It.IsAnySetup调用之外使用该方法,否则它将视为null。将It.IsAny移至设置中应该可以:

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