【问题标题】:How can I create a WebException with an FtpWebResponse for testing?如何使用 FtpWebResponse 创建 WebException 以进行测试?
【发布时间】:2014-07-17 09:26:15
【问题描述】:

我正在使用 FtpWebRequest 和瞬态故障处理应用程序块。对于我的故障处理程序,我有一个错误检测策略来检查响应是否被认为是瞬态的,以便它知道是否重试:

public bool IsTransient(Exception ex)
    {

        var isTransient = false;
        //will be false if the exception is not a web exception.
        var webEx = ex as WebException;

        //happens when receiving a protocol error.
        //This protocol error wraps the inner exception, e.g. a 401 access denied.
        if (webEx != null && webEx.Status == WebExceptionStatus.ProtocolError)
        {
            var response = webEx.Response as FtpWebResponse;
            if (response != null && (int)response.StatusCode < 400)
            {
                isTransient = true;
            }
        }
        // if it is a web exception but not a protocol error,
        // check the status code.
        else if (webEx != null)
        {
            //(check for transient error statuses here...)
            isTransient = true;
        }

        return isTransient;
    }

我正在尝试编写一些测试来检查是否将相应的错误标记为瞬态,但是我在创建或模拟具有 FtpWebResponse 内部异常的 Web 异常时遇到了问题(因此以下并不总是为空)

var response = webEx.Response as FtpWebResponse;

有人知道我该怎么做吗?我的方法正确吗?

【问题讨论】:

    标签: c# unit-testing exception-handling ftpwebresponse


    【解决方案1】:

    WebException 上使用适当的构造函数来设置响应:

    public WebException(
     string message,
     Exception innerException,
     WebExceptionStatus status,
     WebResponse response)
    

    使用 FtpWebResponse 设置异常是我遇到的问题... FtpWebResponse 有一个我无法访问的内部构造函数。

    BCL 并不是真正为测试而设计的,因为该概念在编写时并不大。您必须使用反射调用该内部构造函数(使用反编译器查看可用的内容)。或者,使用自定义可模拟类包装您需要的所有 System.Net 类。不过,这看起来工作量很大。

    【讨论】:

    • 感谢您的回复。这就是我想要使用的,但是使用 FtpWebResponse 设置异常是我遇到的问题...... FtpWebResponse 有一个我无法访问的内部构造函数。
    • 明白。 BCL 并不是真正为测试而设计的,因为该概念在编写时并不大。您必须使用反射调用该内部 ctor(使用反编译器查看可用的内容)。或者,使用自定义可模拟类包装您需要的所有 System.Net 类。不过,这看起来工作量很大。
    • 嗨@usr,您能否将您的评论内容添加到您的答案中?由于时间限制,我最终没有对此进行测试,但我相信您在这里的评论是一个更有帮助的答案。
    【解决方案2】:

    我使用由 Rhino Framework 创建的 FtpWebResponse 存根构建离线测试

    例子:

    public WebException createExceptionHelper(String message, WebExceptionStatus webExceptionStatus, FtpStatusCode serverError )
    {
        var ftpWebResponse = Rhino.Mocks.MockRepository.GenerateStub<FtpWebResponse>();
        ftpWebResponse.Stub(f => f.StatusCode).Return(serverError);
        ftpWebResponse.Stub(f => f.ResponseUri).Return(new Uri("http://mock.localhost"));
    
        //now just pass the ftpWebResponse stub object to the constructor
        return new WebException(message, null, webExceptionStatus, ftpWebResponse);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多