单元测试FTPWebRequest / FTpWebResponse

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

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

unit-testing moq ftpwebrequest ftpwebresponse
3个回答
1
投票

你不能用Moq模拟FTPWebRequestFTPWebResponse,因为它只允许你模拟接口或抽象类。当他们编写大部分System.Net命名空间时,MS看起来并不像是在考虑可测试性。这是我从Moq转移到RhinoMocks的主要原因。

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


0
投票

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不会暴露给世界。)


0
投票

为此,我使用Rhino frameWork。

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

例:

var ftpWebResponse = Rhino.Mocks.MockRepository.GenerateStub<FtpWebResponse>();
ftpWebResponse.Stub(f=>f.StatusCode).Return(FtpStatusCode.AccountNeeded);
© www.soinside.com 2019 - 2024. All rights reserved.