开发者

How to mock DbContext [duplicate]

This question already has an answer here: Unit Testing and Mocking using RhinoMocks (1 answer) Closed 8 years ago.

Here is the code I want to test

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);

}

And here is my test code

[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);
}

Once I run the test I get Null exception for the DbContext on the line

 using (_documentRepository.DbContext.BeginTransaction())
开发者_JAVA百科

The problem I have is I don't have access to the DbContext. How would I go about solving it


As far as I understand you are injecting the repository through the constructor of Document Service as ducumentMockRepository. So you can setup this mock with any expectations you want.

For your case you've to substitute DbContext by mock as well

// 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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜