我正在使用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;有人知道我是怎么做到的吗?我要走正确的路吗?
发布于 2014-07-17 11:20:54
在WebException上使用适当的构造函数设置响应:
public WebException(
string message,
Exception innerException,
WebExceptionStatus status,
WebResponse response)设置FtpWebResponse异常是我遇到麻烦的地方.FtpWebResponse有一个我无法访问的内部构造函数。
BCL并不是真正用于测试的,因为在编写BCL时,这个概念并不大。您必须使用反射调用内部构造函数(使用反编译器查看可用的构造函数)。或者,用自定义的可模拟类包装所需的所有System.Net类。不过,这看起来是一项艰巨的工作。
发布于 2018-02-28 18:36:48
我使用由Rhino创建的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);
}https://stackoverflow.com/questions/24799669
复制相似问题