问题描述
我使用起订量.我模拟了一个类,该类具有如下所示的方法:
I use Moq. I have mocked a class which has method that looks like following:
public async Task DoSomething()
{
// do something...
}
我将其设置如下:
SomeMock.Setup(x => x.DoSomething())
.Callback(() => ... ))
.Returns(Task.FromResult(default(int)));
我不喜欢最后一行:.Returns(Task.FromResult(default(int)))
.有没有一种方法可以以更优雅的方式设置异步返回.我知道有一个方法ReturnsAsync()
,但是它有一个参数.我的方法只返回Task
,所以我没有ReturnsAsync()
的参数.
I don't like last line: .Returns(Task.FromResult(default(int)))
. Is there a way to setup async return in more elegant way. I know there is a method ReturnsAsync()
but it has a parameter. My method returns just Task
so I don't have a parameter for ReturnsAsync()
.
推荐答案
尝试执行以下操作:
someMock.Setup(x => x.DoSomething())
.Callback(() => {})
.Returns(Task.CompletedTask);
请注意,Task.CompletedTask
仅存在于.NET 4.6(最近发布)中或更高版本中.您可以在此 StackOverflow答案中找到更多信息.
Note that Task.CompletedTask
only exists in .NET 4.6 (which was released very recently) or newer. You can find more information in this StackOverflow answer.
ReturnsAsync
用于异步返回值时.当您仅返回Task
时,您实际上根本没有返回任何异步值,因此ReturnsAsync
并没有真正适合"此处.
ReturnsAsync
is for use when you are returning a value asynchronously. When you are returning just a Task
, you are not actually returning any asynchronous value at all, so ReturnsAsync
doesn't really 'fit' here.
如果这不符合您的需求,很遗憾,您将不得不使用Task.FromResult()
.据我所知,这实际上是创建完成的"任务的唯一方法-除了new Task(() => {})
之外的 new Task(() => {})
导致死锁.使用Task.Run(() => {})
.
If this doesn't suit your needs, you will have to use Task.FromResult()
, unfortunately. As far as I know this is really the only way to create a 'completed' task - new Task(() => {})
causes a deadlock. Use Task.Run(() => {})
.
这篇关于没有参数的Moq ReturnAsync()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!