【问题标题】:Unit testing FTPWebRequest/FTpWebResponse单元测试 FTPWebRequest/FTPWebResponse
【发布时间】:2011-03-30 10:39:55
【问题描述】:

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

【问题讨论】:

    标签: unit-testing moq ftpwebrequest ftpwebresponse


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      也不可能使用 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 不会暴露给世界。)

      【讨论】:

        【解决方案3】:

        为此,我使用 Rhino 框架。

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

        例子:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-08
          • 1970-01-01
          • 1970-01-01
          • 2011-07-07
          相关资源
          最近更新 更多