如何模拟 IElasticClient Get 方法?

How to mock the IElasticClient Get method?

这是我的 class 的最小重现,它通过 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 位:IElasticClient returns 上的 Get 方法 null,因此在我的代码之前导致 getResponse.Source 上的 NullReferenceException开始抛出我希望它抛出的异常。

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

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

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