2011-09-30 91 views
1

這裏是我想測試如何嘲笑的DbContext

public DocumentDto SaveDocument(DocumentDto documentDto) 
{ 
    Document document = null; 
    using (_documentRepository.DbContext.BeginTransaction()) 
    { 
     try 
     { 
      if (documentDto.IsDirty) 
      { 
       if (documentDto.Id == 0) 
       { 
        document = CreateNewDocument(documentDto); 
       } 
       else if (documentDto.Id > 0) 
       { 
        document = ChangeExistingDocument(documentDto); 
       } 

       document = _documentRepository.SaveOrUpdate(document); 
       _documentRepository.DbContext.CommitChanges(); 
     } 
    } 
    catch 
    { 
     _documentRepository.DbContext.RollbackTransaction(); 
     throw; 
    } 
} 
return MapperFactory.GetDocumentDto(document); 

}

這裏的代碼是我的測試代碼

[Test] 
public void SaveDocumentsWithNewDocumentWillReturnTheSame() 
{ 
    //Arrange 

    IDocumentService documentService = new DocumentService(_ducumentMockRepository, 
      _identityOfSealMockRepository, _customsOfficeOfTransitMockRepository, 
      _accountMockRepository, _documentGuaranteeMockRepository, 
      _guaranteeMockRepository, _goodsPositionMockRepository); 
    var documentDto = new NctsDepartureNoDto(); 


    //Act 
    var retDocumentDto = documentService.SaveDocument(documentDto); 

    //Assert 
    Assert.AreEqual(documentDto, documentDto); 
} 

一旦運行測試我得到空例外線上的DbContext

using (_documentRepository.DbContext.BeginTransaction()) 

Th我遇到的問題是我無法訪問DbContext。我將如何去解決它

+0

這5個問題 –

+0

他們是非常有用的SLL –

回答

3

據我所知,你通過文件服務的構造函數注入庫爲ducumentMockRepository。 所以你可以設置這個模擬任何你想要的期望。

對於你的情況,你已經通過模擬替代的DbContext以及

// I hope you have an interface to abstract DbContext? 
var dbContextMock = MockRepository.GenerateMock<IDbContext>(); 

// setup expectations for DbContext mock 
dbContextMock.Expect(...) 

// bind mock of the DbContext to property of repository.DbContext 
ducumentMockRepository.Expect(mock => mock.DbContext) 
         .Return(dbContextMock) 
         .Repeat() 
         .Any();