Waldemar Waldemar - 1 year ago 138
C# Question

Setup async Task callback in Moq Framework

I've got an interface which declares

Task DoSomethingAsync();

I'm using MoqFramework for my tests:

public async Task MyAsyncTest()
Mock<ISomeInterface> mock = new Mock<ISomeInterface>();
mock.Setup(arg => arg.DoSomethingAsync()).Callback(() => { <my code here> });

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?

Answer Source

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=...;

Edit: Moq 4.2 has two new extension methods to assist with this.


    .ThrowsAsync(new InvalidOperationException());

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.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download