2013-07-01 37 views
1

我有以下方法。使用Typemock在Nunit中嘲笑IO操作

public string CreateFile(string path, string fileName) 
{ 
    string fullPath = path + "ExportedFiles\\"; 
    if (Directory.Exists(fullPath)) 
    { 
     DirectoryInfo dir = new DirectoryInfo(fullPath); 
     foreach (FileInfo fi in dir.GetFiles()) 
     { 
      fi.Delete(); 
     } 
    } 
    else 
    { 
     Directory.CreateDirectory(fullPath); 
    } 
    string filePath = fullPath + fileName; 
    return filePath; 
} 

我試圖在我的測試用例中使用以下內容。

[Test, Isolated] 
public void TestCreateFileIfPathExists() 
{ 
    Isolate.WhenCalled(() => System.IO.Directory.Exists("gsgs")).WillReturn(true); 
    Isolate.WhenCalled(() => testMyClass.CreateFile(@"D:\testFolder\","TestFile")).CallOriginal(); 
    string result = testMyClass.CreateFile(@"D:\testFolder\", "TestFile"); 
    Assert.AreEqual("D:\\testFolder\\ExportedFiles\\TestFile", result); 
} 

它拋出以下typemock異常。

TypeMock.TypeMockException: *在記錄塊沒有找到方法調用。請檢查:*您是否試圖僞造一個字段而不是一個屬性? *您是否試圖僞造不支持的mscorlib類型?

有什麼辦法可以解決這個問題嗎?

+0

可能的重複[你如何模擬出C#中的文件系統進行單元測試?](http://stackoverflow.com/questions/1087351/how-do-you-mock-out-the-file-system -in-c-sharp-for-unit-testing) –

+0

但他們沒有提到如何使用Typemock來實現這個 – user2435880

+0

你可以分享你的整個單元測試的代碼嗎? –

回答

1

如果你看看你得到異常的最後一個問題,

*您正試圖僞造一個不支持的mscorlib類型?

存在例外,其內容

見支持的類型這裏後實際網址:http://www.typemock.com/mscorlib-types

當你去那裏,你會發現:

enter image description here

明顯缺席fr這個列表是System.IO.Directory類,在撰寫本文時似乎不支持TypeMock。這是導致你的錯誤的線。

+0

那麼有什麼辦法解決這個問題? – user2435880

+0

@ user2435880我知道的唯一方法是在你的代碼和代碼之間創建一個抽象層,就像[你如何在C#中嘲笑文件系統進行單元測試?](http://問題/ 1088351)。 –