首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何模拟DbContext

如何模拟DbContext
EN

Stack Overflow用户
提问于 2011-09-30 19:02:43
回答 1查看 9K关注 0票数 1

下面是我想要测试的代码

代码语言:javascript
复制
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);

}

下面是我的测试代码

代码语言:javascript
复制
[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的空异常

代码语言:javascript
复制
 using (_documentRepository.DbContext.BeginTransaction())

我的问题是我不能访问DbContext。我该如何去解决它呢?

EN

回答 1

Stack Overflow用户

发布于 2011-09-30 20:41:18

据我所知,您是通过文档服务的构造器ducumentMockRepository注入存储库的。所以你可以用你想要的任何期望来设置这个模拟。

对于您的情况,也必须将DbContext替换为mock

代码语言:javascript
复制
// 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();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7609430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档