在起订量Framework安装任务异步回调 [英] Setup async Task callback in Moq Framework

查看:155
本文介绍了在起订量Framework安装任务异步回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有它声明的接口

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> });
   ...
}

然后在我的测试我执行代码,调用等待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, eg:

MyType someValue=...;
mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.FromResult(someValue));

修改:起订量4.2有两个新的扩展方法,以协助这一点。

Edit: 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());



编辑2 作为塞思花卉提到了对方的回答, ReturnsAsync 仅适用于返回任务的方法。对于只返回一个工作方法, .Returns(Task.FromResult(默认值(对象)))可以使用。

Edit 2 As Seth Flowers mentions in the other answer, ReturnsAsync is only available for methods that return a Task. For methods that return only a Task, .Returns(Task.FromResult(default(object))) can be used.

这个答案所示,在.NET 4.6它被简化成 .Returns( Task.CompletedTask); ,例如:

As shown in this answer, in .NET 4.6 this is simplified to .Returns(Task.CompletedTask);, eg:

mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.CompletedTask);

这篇关于在起订量Framework安装任务异步回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆