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?
Moq supports mocking protected methods. Changing the methods to protected , instead of private , would allow you to mock their implementation.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With