使用异步和包含模拟 EF

Mocking EF with async and Include

我正在尝试嘲笑 Entity Framework。我的方法包括异步和使用 2 个 EF 表。 我的方法 (MyClass.Create):

                        var my = new Application(title, "", creatorId, documentId, deadLine);
                        var document = await _db.Documents.FindAsync(my.DocumentId);
//some stuffs
//....
                        _db.My.Add(my);
                        await _db.SaveChangesAsync();

测试:

        private ApplicationDbContext context;
        private DbSet<My> my;
        private DbSet<Document> document;
        private Document mDocument;
        [SetUp]
        public void Initialize()
        {
            // Instantiate mocks
            context = MockRepository.GenerateMock<ApplicationDbContext>();
            my = MockRepository.GenerateMock<DbSet<My>>();
            document = MockRepository.GenerateMock<DbSet<Document>>();
            mDocument = new Document(Guid.NewGuid().ToString(), "Про тест", "123456", Guid.NewGuid().ToString(), "12345", DateTime.Now, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
            // Setup unit of work to return mocked repository
            context.Stub(uow => uow.My).Return(my);
            context.Stub(uow => uow.Documents).Return(document);
        }
        [Test]
        public async Task Create_Consideration()
        {
            // Arrange
            document.Stub(doc => doc.FindAsync(Arg<int>.Is.Anything)).Return(Task.FromResult(mDocument));

            my.Expect(svc => svc.Add(Arg<My>.Is.Anything));
            context.Expect(svc => svc.SaveChanges());

            // Act
            await MyClass.Create("Test", mDocument.CreatorId, mDocument.Id);

            //Assert
            my.VerifyAllExpectations();
            context.VerifyAllExpectations();
        }
    }

我得到的错误:方法'DbContext.SaveChangesAsync();'需要一个return值或一个异常来抛出

测试必须如下所示:

        my.Expect(svc => svc.Add(Arg<My>.Is.Anything));
        context.Expect(svc => svc.SaveChangesAsync()).Return(Task.FromResult(Arg<int>.Is.GreaterThanOrEqual(0)));

        // Act
        await consideration.Create("Test", mDocument.CreatorId, mDocument.Id, null, new List<string> { cUser.Id, cUser2.Id });

        //Assert
        my.VerifyAllExpectations();
        context.VerifyAllExpectations();