如何模拟DbContext
本文关键字:DbContext 模拟 何模拟 | 更新日期: 2023-09-27 18:10:19
下面是我要测试的代码
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。如何求解呢
据我所知,您是通过Document Service的构造函数作为ducumentMockRepository
注入存储库的。因此,您可以用任何期望设置这个mock。
对于您的情况,您必须将DbContext替换为mock
// 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();