Hugh Janus Hugh Janus - 3 years ago 126
C# Question

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

When I use

ReturnsAsync(null)
in a C# unit test method in Visual Studio (with
Moq
), I get the error:


"The call is ambiguous between the following methods or properties"


and then a list of the
ReturnsAsync
methods which have different parameters. I understand that this is due to the
ReturnsAsync
function being overloaded. However, when I run the same unit test on my colleague's computer, it runs without any errors. Does anyone know why this would happen? Does anyone know how to fix this?

Also, when I build, I get warnings that:


all packages referencing ******** must install nuget package Microsoft.Bcl.Build.


Could that have any effect?

Answer Source

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

RetursAsync((string)null)

Or you can pass value which is null

string s = null;
... ReturnsAsync(s);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download