I have
Service.Setup(service => service.AsyncMethod(It.IsAny<Func<Task>>()));
where Service is a Mock and AsyncMethod accepts a Func<Task>
and returns a Task
. Normally in my code I simply await service.AsyncMethod(..)
.
When I run this code as a Unit Test in Moq, it fails, giving me an exception invocation failed with mock behavior Strict. Invocation needs to return a value and therefore must have a corresponding setup that provides it.
Okay sure, I need to return a value. Then why can't I do
Service.Setup(service => service.AsyncMethod(It.IsAny<Func<Task>>())).Returns(..)
at all? It tells me that it cannot resolve the symbol 'Returns'. I don't understand what I'm doing wrong...
It can be done such way:
Service.Setup(service => service.AsyncMethod(It.IsAny<Func<Task>>()))
.Returns(Task.CompletedTask);
Solved my own question.
I have an interface Service
interface IService
{
Task asyncMethod(Func<Task> asyncFunc);
}
My Moq is like so
Mock<IService> Service = new Mock<IService>(MockBehavior.Strict);
Service.Setup(service => service.AsyncMethod(It.IsAny<Func<Task>>()));
I cannot specify a .Returns()
value for the Setup because it doesn't understand the syntax, 'Returns' symbol not recognized. Changing it to this fixes it.
Service.Setup<Task>(service => service.AsyncMethod(It.IsAny<Func<Task>>()))
.Returns<Func<Task>>(async (asyncFunc) => await asyncFunc.Invoke());
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