2009-05-11 9 views
2

私はファイルの単体テスト保存しようとしています。私は、ドキュメントを定義するインターフェイスを持って、私はSaveメソッドにそのインターフェイスを実装する具体的なオブジェクトを渡し、それは実際に動作しますが、私はそれが常に動作することを確認するためにテストしようとしている(そして、私は絶望的に「クランチタイム」の期間を過ぎて単体テストに追いつこうとしていました)。mockedインターフェイスはまだファイルにシリアル化されますか?

public Boolean SaveDocument(IDocument document) 
{ 
    BinaryFormatter bFormatter = new BinaryFormatter(); 
    FileStream fs = null; 

    try 
    { 
     if (!Directory.Exists(folderName)) 
      Directory.CreateDirectory(folderName); 

     String path = Path.Combine(Path.Combine(folderName, document.FileName), document.Extension); 
     using (fs = new FileStream(path, FileMode.OpenOrCreate)) 
     { 
      bFormatter.Serialize(fs, document); 
     } 
    } 
    catch (IOException ioex) 
    { 
     LOG.Write(ioex.Message); 
     return false; 
    } 

    return true; 
} 

と私のテストは、次のとおりです:

[Test] 
public void can_save_a_document() 
{ 
    String testDirectory = "C:\\Test\\"; 
    m_DocumentHandler = new DocumentHandler(testDirectory); 

    DynamicMock mock = new DynamicMock(typeof(IDocument)); 

    mock.ExpectAndReturn("get_FileName", "Test_File"); 
    mock.ExpectAndReturn("get_Extension", ".TST"); 

    m_DocumentHandler.SaveDocument(mock.MockInstance as IDocument); 

    try 
    {  
     Assert.IsTrue(Directory.Exists(testDirectory), "Directory was not created"); 
     String[] filesInTestDir = Directory.GetFiles(testDirectory); 

     Assert.AreEqual(1, filesInTestDir.Length, "there is " + filesInTestDir.Length.ToString() + " files in the folder, instead of 1"); 
     Assert.AreEqual(Path.GetFileName(filesInTestDir[0]), "Test_File.TST"); 
    } 
    finally 
    { 
     Directory.Delete(testDirectory); 
     Assert.IsFalse(Directory.Exists(testDirectory), "folder was not cleaned up"); 
    } 
} 

私はインターフェイスpreserves the concrete dataをシリアル化することを認識してんだけど、インターフェイスを嘲笑するメソッドを保存するマイ

それはそうのように動作し、非常に単純ですシリアライズ?

答えて

1

BinaryFormatterは、データをシリアル化するときに、インターフェイスではなく渡されたオブジェクトの実際の型を使用します。そこで内部的には、実際のオブジェクトを渡すときにはMyLib.Objects.MyObj、MyLibのようなものを書いて、モックオブジェクトを渡すときはType:Moq.ConcreteProxy、Moqなどを書きます。

永続性のためにBinaryFormatterを使用すると、リリース間のバージョニングとメモリレイアウトの違いに対処する必要があります。文書のための明確なフォーマットを確立し、オブジェクトとフィールドを手作業で書く方がはるかに良いでしょう。

0

クラスでシリアル化がどのように機能するかをテストする必要がある場合は、テスト用の実際のクラスをいくつか作成し、それらを使用します。 Mockingは、コラボレーションするオブジェクト間の対話をテストするのに便利です。

関連する問題