[英]Moq callbase for async methods don't work
I have class which is mocked but in some cases I need to run original method 我有被嘲笑的类,但在某些情况下,我需要运行原始方法
public virtual async Task<int> SaveChangesAsync(string userId)
{
try
{
TrackChanges(userId);//sets some fields
return await db.SaveChangesAsync();
}
catch (Exception e)
{
LogSaveValidationFailed(e);
throw;
}
}
I have tried CallBase = true
, but it don't work for async
methods, also tried workaround with CallBack
... 我已经尝试过
CallBase = true
,但是它不适用于async
方法,还尝试了CallBack
解决方法...
var db = new Mock<DbContext>();
db.CallBase = true;
db.Setup(x => x.SaveChangesAsync(It.IsAny<string>())).ReturnsAsync(1).Callback((string user) =>
{
db.Object.SaveChanges(user);
});
...it returns value bud never call callback. ...它返回值bud永远不会调用回调。 Everything works normal method but doesn't work with async.
一切工作正常的方法,但不适用于异步。 What can I do to make it work with Moq, or it's better just refactor a bit and move
TrackChanges
from async method to normal? 我该怎么做才能使其与Moq一起使用,还是最好重构一下并将
TrackChanges
从async方法移到普通方法?
I know that the documentation says you can do 我知道文档说你可以做
db.CallBase = true
db.CallBase = true
but I have never used that approach myself. 但我自己从未使用过这种方法。 This is how I partially mock a class and it works good.
这就是我部分模拟课程的方式,并且效果很好。
[TestClass]
public class MyClassTest
{
[TestMethod]
public async Task MyClass_ReturnsCorrectValues()
{
// Arrange
var m = new Mock<MyClass>();
m.Setup(x => x.IsKing())
.Returns(Task.FromResult(true));
m.Setup(x => x.IsQueen())
.CallBase();
// Act
var isKing = await m.Object.IsKing();
var isQueen = await m.Object.IsQueen();
// Assert
Assert.IsTrue(isKing); // true
Assert.IsFalse(isQueen); // false
}
}
public class MyClass
{
public virtual async Task<bool> IsKing()
{
return await Task.FromResult(false);
}
public virtual async Task<bool> IsQueen()
{
return await Task.FromResult(false);
}
}
呵呵,实际上与db.CallBase = true一起工作,但是当还有db.setup()。callbase()时失败
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.