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

私が理解している限り、あなたはDocumentServiceのコンストラクターを介してリポジトリーを注入しています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 に答える