Steffen Steffen - 2 months ago 9
C# Question

How to mock function returning void task

I have a function

public Task DoSomethingAsync();


which I want to mock for testing purposes.

What is the right way to implement the return value of such a method. If it would return
Task<int>
or something, I would use
Task.FromResult<int>(5);


I could do

public async void DoSomethingAsync()
{
//implementation
}


This however lacks the await operator and will (at least with Resharper) be underlined.

What is the correct way to return a task here?

Answer

All you need to do is to return a Task and (surprise! :-)) Task<T> derives from Task, it is a Task. See this reference.

So just return a bool (or anything else):

return Task.FromResult(true);

You could also return a completed Task by using:

return Task.CompletedTask;

(Note: the above is only available as of .NET 4.6)