Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq fails because it expects a return value but doesn't let me provide it

Tags:

c#

testing

moq

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...

like image 222
dBlisse Avatar asked Aug 15 '14 20:08

dBlisse


2 Answers

It can be done such way:

Service.Setup(service => service.AsyncMethod(It.IsAny<Func<Task>>()))
    .Returns(Task.CompletedTask);
like image 182
Neshta Avatar answered Oct 05 '22 08:10

Neshta


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());
like image 23
dBlisse Avatar answered Oct 05 '22 07:10

dBlisse