这是我班级的最小代表,通过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
方法?
答案 0 :(得分:4)
您不能在It.IsAny
调用之外使用Setup
方法,否则会将其视为null。将It.IsAny
移动到设置中应该有效:
clientMock
.Setup(c => c.Get<Person>(It.IsAny<Func<GetDescriptor<Person>, GetDescriptor<Person>>>()))
.Returns(getRetvalMock.Object);