处理内部异常的属性?

时间:2011-06-25 18:36:25

标签: c# exception exception-handling inner-exception

我正在为WCF Web服务编写单元测试。我故意向服务器发送无效请求,该服务器抛出WebExceptionFault<string>。在单元测试中,被捕获的异常是EndpointNotFoundExceptionWebException属性中具有标准InnerException。我想验证响应的主体是否匹配我认为应该存在的字符串。

然而,我遇到了一个问题,因为ResponseWebException)的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的属性?有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:0)

似乎是异常序列化问题。您可能必须在服务器上捕获错误并自定义构建错误消息

How to serialize an Exception object in C#?