Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 381
Justin Borromeo Avatar asked Jan 13 '17 13:01

Justin Borromeo


People also ask

Can you mock a private method MOQ?

Moq supports mocking protected methods. Changing the methods to protected , instead of private , would allow you to mock their implementation.

What is MOQ unit testing in C#?

Moq is a mocking framework built to facilitate the testing of components with dependencies. As shown earlier, dealing with dependencies could be cumbersome because it requires the creation of test doubles like fakes. Moq makes the creation of fakes redundant by using dynamically generated types.

How does MOQ mock work?

Mock objects allow you to mimic the behavior of classes and interfaces, letting the code in the test interact with them as if they were real. This isolates the code you're testing, ensuring that it works on its own and that no other code will make the tests fail.


1 Answers

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); 
like image 117
Sergey Berezovskiy Avatar answered Sep 18 '22 05:09

Sergey Berezovskiy