【发布时间】:2018-11-10 09:08:15
【问题描述】:
当 Nest 在 IGetResponse.OriginalException 属性中具有值时,我正在尝试测试某些异常的结果。
我首先设置了响应:
var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(new Exception("Status code 404"));
然后是假弹性客户端:
var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
.WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
.Returns(response);
客户端被注入到我正在测试的类中。
但是,在单步执行代码时,调用客户端时会返回伪造的响应,但 OriginalException getter 没有任何价值。它不为空,但所有属性都没有任何值。我期待 OriginalException.Message 等于 状态码 404。
我也尝试将响应对象设置为:
var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");
...同样糟糕的结果。
如何设置IGetResponse,以便我可以在正在测试的课程中评估OriginalException.Message?
请求了更多代码。我可以展示整个测试,我会展示正在测试的方法。这是我的整个测试:
[TestMethod]
[ExpectedException(typeof(NotFoundException))]
public void Get_ClientReturns404_ThrowsNotFoundException()
{
// setup
var request = new DataGetRequest
{
CollectionName = string.Empty,
DocumentType = string.Empty,
DataAccessType = string.Empty
};
var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");
var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
.WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
.Returns(response);
var elasticSearch = new ElasticSearch(null, client);
// test
var result = elasticSearch.Get(request);
// assert
Assert.Fail("Should have hit an exception.");
}
}
这是正在测试的方法:
public async Task<Dictionary<string, object>> Get(DataGetRequest getRequest)
{
GetRequest request = new GetRequest(getRequest.CollectionName, getRequest.DocumentType, getRequest.Id);
var response = await Client.GetAsync<Dictionary<string, object>>(request);
if (response.OriginalException != null)
{
var message = response.OriginalException.Message;
if (message.Contains("Status code 404"))
throw new NotFoundException(String.Format("Not Found for id {0}", getRequest.Id));
else
throw new Exception(message);
}
return response.Source;
}
IF 块中的错误处理不是很健壮。一旦单元测试成功,那么代码可能会受到更多的喜爱。
【问题讨论】:
-
什么都没有出现。你能粘贴更多代码吗?理想情况下是一个可运行的测试,但至少你如何将客户端注入到你正在测试的类中,你如何调用那个类,以及被调用的方法是做什么的?
-
@BlairConrad 完成。不知道会有多大帮助,但你永远不知道。
标签: c# mstest nest fakeiteasy