我正在尝试模拟实体框架。我的方法包括Async和使用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();'需要返回值或抛出异常
答案 0 :(得分:0)
测试必须如下所示:
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();