Daniel Allen Langdon Daniel Allen Langdon - 19 days ago 7
C# Question

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.

Answer

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;
Comments