Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 806
Steffen Avatar asked Sep 22 '16 12:09

Steffen


2 Answers

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)

like image 95
Krumelur Avatar answered Sep 21 '22 01:09

Krumelur


You can return Task.CompletedTask (.net 4.6 required) or simply Task.FromResult(true)

The idea is just to return a Task

like image 41
AD.Net Avatar answered Sep 21 '22 01:09

AD.Net