如何告诉 Moq 返回任务? [英] How can I tell Moq to return a Task?
问题描述
我有一个接口声明
Task DoSomethingAsync();
我使用 MoqFramework 进行测试:
I'm using MoqFramework for my tests:
[TestMethod()]
public async Task MyAsyncTest()
{
Mock<ISomeInterface> mock = new Mock<ISomeInterface>();
mock.Setup(arg => arg.DoSomethingAsync()).Callback(() => { <my code here> });
...
}
然后在我的测试中,我执行调用 await DoSomethingAsync()
的代码.并且测试只是在那条线上失败了.我做错了什么?
Then in my test I execute the code which invokes await DoSomethingAsync()
. And the test just fails on that line. What am I doing wrong?
推荐答案
您的方法没有任何回调,因此没有理由使用 .CallBack()
.您可以使用 .Returns()
和 Task.FromResult,例如:
Your method doesn't have any callbacks so there is no reason to use .CallBack()
. You can simply return a Task with the desired values using .Returns()
and Task.FromResult, e.g.:
MyType someValue=...;
mock.Setup(arg=>arg.DoSomethingAsync())
.Returns(Task.FromResult(someValue));
更新 2014-06-22
Moq 4.2 有两个新的扩展方法来帮助解决这个问题.
Moq 4.2 has two new extension methods to assist with this.
mock.Setup(arg=>arg.DoSomethingAsync())
.ReturnsAsync(someValue);
mock.Setup(arg=>arg.DoSomethingAsync())
.ThrowsAsync(new InvalidOperationException());
更新 2016-05-05
正如 Seth Flowers 在其他答案中提到的那样,ReturnsAsync
仅适用于返回一个 Task
.对于只返回一个 Task 的方法,
As Seth Flowers mentions in the other answer, ReturnsAsync
is only available for methods that return a Task<T>
. For methods that return only a Task,
.Returns(Task.FromResult(default(object)))
可以使用.
如这个答案所示,在.NET 4.6中,这被简化为.Returns(Task.CompletedTask);
,例如:
As shown in this answer, in .NET 4.6 this is simplified to .Returns(Task.CompletedTask);
, e.g.:
mock.Setup(arg=>arg.DoSomethingAsync())
.Returns(Task.CompletedTask);
这篇关于如何告诉 Moq 返回任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!