1

这是我要测试的代码

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。我将如何解决它

4

1 回答 1

3

据我了解,您是通过 Document Service 的构造函数将存储库注入为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();
于 2011-09-30T12:41:18.050 回答