Unit testing 单元测试FTPWebRequest/FTpWebResponse

Unit testing 单元测试FTPWebRequest/FTpWebResponse,unit-testing,moq,ftpwebrequest,ftpwebresponse,Unit Testing,Moq,Ftpwebrequest,Ftpwebresponse,如何通过MOQ对FTPWebRequest和FTPWebResponse进行单元测试。您不能使用MOQ或MOQ进行模拟,因为它只允许您模拟接口或抽象类。而且看起来MS在编写System.Net命名空间的大部分内容时并没有考虑可测试性。这就是我从Moq转向Rhinomock的主要原因 您需要构建自己的FTPWeb*对象并将其传递给处理程序。使用Mock也不可能,因为FTPWebResponse没有公开构造函数以允许从中派生某些内容 下面是我在类似情况下编写测试的方式 测试方法:ExceptionC

如何通过MOQ对FTPWebRequest和FTPWebResponse进行单元测试。

您不能使用MOQ或MOQ进行模拟,因为它只允许您模拟接口或抽象类。而且看起来MS在编写System.Net命名空间的大部分内容时并没有考虑可测试性。这就是我从Moq转向Rhinomock的主要原因


您需要构建自己的FTPWeb*对象并将其传递给处理程序。

使用Mock也不可能,因为
FTPWebResponse
没有公开构造函数以允许从中派生某些内容

下面是我在类似情况下编写测试的方式

测试方法:
ExceptionContainsFileNotFound(ExceptionEx)
包含以下逻辑:

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框架

即使没有公共构造函数、只读属性等,它也可以处理实例创建

例如:

var ftpWebResponse = Rhino.Mocks.MockRepository.GenerateStub<FtpWebResponse>();
ftpWebResponse.Stub(f=>f.StatusCode).Return(FtpStatusCode.AccountNeeded);
var ftpWebResponse=Rhino.Mocks.MockRepository.GenerateSub();
ftpWebResponse.Stub(f=>f.StatusCode).Return(FtpStatusCode.AccountRequired);