2009-05-11 4 views
2

파일의 단위 테스트 저장을 시도하고 있습니다. 문서를 정의하는 인터페이스가 있고 저장 메서드에 해당 인터페이스를 구현하는 구체적인 개체를 전달하고 실제로 작동하지만 단색 테스트를 통해 항상 작동하는지 확인하려고합니다. 필자는 '위기 시간'이후 단위 테스트를 따라 잡기 위해 필사적으로 노력했다).조롱 된 인터페이스가 여전히 파일에 직렬화됩니까?

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는 데이터를 직렬화 할 때 전달 된 객체의 실제 유형 (인터페이스가 아닌)을 사용합니다. 따라서 내부적으로 실제 객체를 전달할 때 Type : MyLib.Objects.MyObj, MyLib과 같은 것을 쓸 것이며 mock 객체를 전달할 때 Type : Moq.ConcreteProxy, Moq 등을 쓸 것입니다.

지속성을 위해 BinaryFormatter를 사용하면 릴리스 간의 버전 및 메모리 레이아웃 차이를 처리해야하므로 문제가 발생합니다. 문서를 잘 정의 된 형식으로 설정하고 객체와 필드를 수동으로 작성하는 것이 훨씬 낫습니다.

0

클래스에서 직렬화가 작동하는 방식을 테스트해야하는 경우 테스트를위한 실제 클래스를 만들어이를 사용하십시오. 조롱은 공동 작업하는 개체 간의 상호 작용을 테스트하는 데 유용합니다.