首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何创建一个带有WebException的FtpWebResponse来进行测试?

如何创建一个带有WebException的FtpWebResponse来进行测试?
EN

Stack Overflow用户
提问于 2014-07-17 09:26:15
回答 2查看 1.1K关注 0票数 2

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

代码语言:javascript
运行
复制
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异常时遇到了困难(这样,下面的响应并不总是为空)

代码语言:javascript
运行
复制
var response = webEx.Response as FtpWebResponse;

有人知道我是怎么做到的吗?我要走正确的路吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-07-17 11:20:54

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

代码语言:javascript
运行
复制
public WebException(
 string message,
 Exception innerException,
 WebExceptionStatus status,
 WebResponse response)

设置FtpWebResponse异常是我遇到麻烦的地方.FtpWebResponse有一个我无法访问的内部构造函数。

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

票数 2
EN

Stack Overflow用户

发布于 2018-02-28 18:36:48

我使用由Rhino创建的FtpWebResponse存根构建脱机测试

示例:

代码语言:javascript
运行
复制
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);
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24799669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档