HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How can I tell Moq to return a Task?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
moqhowreturncantelltask

Problem

I've got an interface which declares

Task DoSomethingAsync();


I'm using MoqFramework for my tests:

[TestMethod()]
public async Task MyAsyncTest()
{
   Mock mock = new Mock();
   mock.Setup(arg => arg.DoSomethingAsync()).Callback(() => {  });
   ...
}


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?

Solution

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


Update 2014-06-22

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


Update 2016-05-05

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.

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

Code Snippets

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

mock.Setup(arg=>arg.DoSomethingAsync())        
    .ThrowsAsync(new InvalidOperationException());
.Returns(Task.FromResult(default(object)))
mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.CompletedTask);

Context

Stack Overflow Q#21253523, score: 951

Revisions (0)

No revisions yet.