0
我試圖嘲笑實體框架。我的方法包括異步和2個EF表。 我的方法(MyClass.Create):嘲笑EF與異步和包括
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();'需要一個返回值或異常拋出
問題是此行'使用(VAR _db =新ApplicationDbContext())'。您正在創建一個新的ApplicationDbContext。你不使用你的嘲弄上下文 – Jehof 2015-03-25 11:15:59
其幫助我改變這段代碼,但現在錯誤:方法'DbContext.SaveChangesAsync();'需要返回值或拋出的異常 – NoNameR 2015-03-25 12:24:29
您需要像mockObj.Setup(a => a.SaveChangesAsync())一樣模擬方法「SaveChangesAsync」。或實施回撥行動 – 2015-03-25 13:08:50