Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a mock Task object for testing purposes in C#?

I'm trying to write a unit test that must mock an async method that returns Task.

In the past, I had to mock an async method that returns Task<T>. For that, I could use Task.FromResult<T>(t), but I don't see that it works with Task. (See here: Stubbing Task returning method in async unit test)

One thing I've found that seems to work is Task.Delay(0), but that seems rather hackish.

What is the proper way to create a mock Task object for testing purposes in C#?

I simply need a Task that indicates that the task completed, but in future cases, I might need a Task that indicates that an exception was raised or a Task that never completes.

like image 899
Vivian River Avatar asked Oct 26 '25 04:10

Vivian River


1 Answers

Since Task<T> is a sub type of Task you can use Task.FromResult and it should work just fine:

Task fakeTask = Task.FromResult<object>(null);

Another option is to use Task.CompletedTask Property which was made exactly for this purpose:

Task completedTask = Task.CompletedTask;
like image 88
YuvShap Avatar answered Oct 28 '25 16:10

YuvShap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!