如何模拟DbContext

时间:2011-09-30 11:02:43

标签: c# entity-framework unit-testing nunit 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的Null异常
 using (_documentRepository.DbContext.BeginTransaction())

我遇到的问题是我无法访问DbContext。我将如何解决它

1 个答案:

答案 0 :(得分:3)

据我所知,您通过文档服务的构造函数将注册表注入ducumentMockRepository。 因此,您可以根据自己的期望设置此模拟。

对于你的情况,你也要用mock替换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();