Returnsasync(null) throws a build error when using Moq for unit testing in VS15

There are two ReturnsAsync extension methods in Moq ReturnsExtensions class.They have following parameters:

(this IReturns<TMock, Task<TResult>> mock, TResult value)
(this IReturns<TMock, Task<TResult>> mock, Func<TResult> valueFunction)

As you can see one accepts value which should be returned by task, and another accepts delegate which will return value. When you are passing null compiler don’t know whether it value or delegate. It’s not the case when task parameter is a value type (e.g. int). Because it cannot be null and compiler understands that null is a delegate. Probably that’s the case with your colleague’s computer.

To fix this error you need to help compiler choose correct method overload – cast null to type of task’s result (e.g. string):


Or you can pass value which is null

string s = null;
... ReturnsAsync(s);

Leave a Comment