我正在为WCF Web服务编写单元测试。我故意向服务器发送无效请求,该服务器抛出WebExceptionFault<string>
。在单元测试中,被捕获的异常是EndpointNotFoundException
,WebException
属性中具有标准InnerException
。我想验证响应的主体是否匹配我认为应该存在的字符串。
然而,我遇到了一个问题,因为Response
(WebException
)的System.Net.SyncMemoryStream
属性已被处理,无法读取。
我的代码:
Clubs actual;
try
{
//"201" is an invalid argument for the first parameter
actual = new Clubs(channel.GetClubs("201", "123"));
}
catch (EndpointNotFoundException e)
{
WebException w = e.InnerException as WebException;
Assert.IsNotNull(w);
HttpWebResponse resp = w.Response as HttpWebResponse;
Assert.IsNotNull(resp);
Assert.AreEqual(resp.StatusCode, HttpStatusCode.NotFound);
//Next line throws an ArgumentException saying Stream not readable
//Investigation shows it has been disposed
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
Assert.AreEqual(sr.ReadToEnd(), "League not allowed for selected club");
}
是否正常处理InnerException的属性?有没有办法解决这个问题?