本文介绍了如何告诉Moq返回任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个声明的接口

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<T>的方法. .对于仅返回任务的方法,

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返回任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:28