2011-03-30 24 views

回答

1

你不能模擬FTPWebRequestFTPWebResponse與Moq,因爲它只允許你模擬接口或抽象類。當他們編寫大部分System.Net命名空間時,它並不像MS想到可測試性。這是我從Moq轉移到RhinoMocks的主要原因。

您需要構建自己的FTPWeb *對象並將它們傳遞給您的處理程序。

+0

是啊,我剛發現。感謝您的答覆。 – 2011-03-30 11:03:26

+0

你會如何使用RhinoMocks來模擬ftprequest?謝謝 – 2011-03-30 11:10:22

0

模擬也是不可能的,因爲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

對於我使用犀牛框架。

即使沒有公共構造函數,只讀屬性等,它也可以處理實例創建。

例子:

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