如何使用FtpWebResponse创建WebException进行测试?

问题描述 投票:2回答:2

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

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异常时遇到问题(以便以下内容中的响应不是' t总是空的)

var response = webEx.Response as FtpWebResponse;

有人知道我怎么做吗?我是以正确的方式去做的吗?

c# unit-testing exception-handling ftpwebresponse
2个回答
2
投票

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

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

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

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


0
投票

我使用由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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.