单元测试 FTPWebRequest/FTPWebResponse
-
14-11-2019 - |
题
您将如何通过最小起订量对 FTPWebRequest 和 FTPWebResponse 进行单元测试。
没有正确的解决方案
其他提示
你不能mock ftpwebroquest 或 ftpwebrespons 使用moq,因为它只允许您模拟接口或抽象课程。它看起来并不像MS在写入大部分System.net命名空间时正在考虑可测试性。这是我远离Moq到Rhinocks的主要原因。
您需要构建自己的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 不会暴露给世界。)
我使用犀牛框架。
它可以处理实例创建即使没有公共构造函数,只读属性等。
示例:
var ftpWebResponse = Rhino.Mocks.MockRepository.GenerateStub<FtpWebResponse>();
ftpWebResponse.Stub(f=>f.StatusCode).Return(FtpStatusCode.AccountNeeded);
. 不隶属于 StackOverflow