How do I setup an async method which only returns a Task in strict mode in Moq 4.13.1?

Viewed 260

I have an async method returning a Task:

public virtual async Task IReturnATask(Guid settingId)

When I try to set it up like this in my unit test,

_service.Setup(m => m.IReturnATask(guid));

Moq complains:

"Invocation needs to return a value and therefore must have a corresponding setup that provides it."

How should I define the setup of this async method?

1 Answers

A Task is still needed to allow the await to flow to completion when exercising the test.

So it needs to be setup to return a Task.

Task.CompletedTask can be used for this

//...

_service
    .Setup(m => m.IReturnATask(It.Any<Guid>()))
    .Returns(Task.CompletedTask);

//...
Related