Mocking (stubbing) async calls (async/await)

Test Driven Development, Testing, C#, .Net

.Net 4.5 came out with a really handy built-in asynchronous mechanism, async and await. However the method signature of a void method is a bit strange:

It is possible to use async void but it’s not recommended unless we are talking about event handlers. It’s also a bit strange the fact that the type specified in the signature is not the one returned:

But everything else is great and very handy.

Stubbing method calls can be hard though. You can get weird exceptions like System.AggregateException when running tests with NUnit. The problem comes up when awaiting for a

stubbed async method:

The problem is that Moq will make the stubbed method return null when invoked, because we are not specifying any return value. The default value for Task is null. We should tell Moq to return a proper Task:

The key is to return a new task: Task.Factory.StartNew(lambda)

Originally published in Carlos Blé's blog.