单元测试FTPWebRequest / FTpWebResponse

您将如何通过MOQ对FTPWebRequest和FTPWebResponse进行单元测试。     
已邀请:
你不能用Moq模拟FTPWebRequest或FTPWebResponse,因为它只允许你模拟接口或抽象类。当他们编写大部分System.Net命名空间时,MS看起来并不像是在考虑可测试性。这是我从Moq转移到RhinoMocks的主要原因。 您需要构建自己的FTPWeb *对象并将它们传递给处理程序。     
Mock也不可能,因为
FTPWebResponse
没有暴露的构造函数允许从中派生出来。 以下是我在类似情况下编写测试的方法。 测试方法:
ExceptionContainsFileNotFound(Exception ex)
包含以下逻辑:
if (ex is WebException)
{
    var response = (ex as WebException).Response;
    if (response is FtpWebResponse)
    {
        if ((response as FtpWebResponse).StatusCode == FtpFileNotFoundStatus)
        {
            return true;
        }
    }
}
为了测试它,我实现了快速技巧。
try
{
    var request = WebRequest.Create("ftp://notexistingfptsite/");
    request.Method = WebRequestMethods.Ftp.ListDirectory;

    request.GetResponse();
}
catch (WebException e)
{
    // trick :)
    classUnderTest.FtpFileNotFoundStatus = FtpStatusCode.Undefined;

    var fileNotFoundStatus = classUnderTest.ExceptionContainsFileNotFound(e);

    Assert.That(fileNotFoundStatus, Is.True);
}
(当然FtpFileNotFoundStatus不会暴露给世界。)     
为此,我使用Rhino frameWork。 即使没有公共构造函数,只读属性等,它也可以处理实例创建。 例:
var ftpWebResponse = Rhino.Mocks.MockRepository.GenerateStub<FtpWebResponse>();
ftpWebResponse.Stub(f=>f.StatusCode).Return(FtpStatusCode.AccountNeeded);
    

要回复问题请先登录注册