Steffen Steffen - 1 year ago 98
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
or something, I would use

I could do

public async void DoSomethingAsync()

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 Source

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)