我正在编写一个单元测试方法,对在我的测试条件下预计会抛出具有特定响应消息的HttpResponseException的代码进行测试。
我的测试方法代码的相关部分如下:
try
{
MyClassBeingTested.MyWebServiceMethodBeingTested(myParameters);
}
catch (HttpResponseException ex)
{
string errorMessage = await ex.Response.Content.ReadAsStringAsync();
Assert.IsTrue(errorMessage.Contains("My expected error message string"));
return;
}
Assert.Fail("Expected HttpResponseException didn't get thrown");
这段代码可以正常工作,测试也通过了。
然而,我希望更好地理解为什么需要以这种方式构造读取错误消息的代码。HttpResponseException类只提供其消息的异步访问方式。因此,我需要通过ReadAsStringAsync()
来获取消息,而不能像通过ex.Response.Content.Message
这样同步获取消息。
我觉得自己可能没有理解HttpResponseException类的工作方式。 为什么HttpResponseException不提供对其响应消息的同步访问?