Vivian River
Vivian River

Reputation: 32380

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.

Upvotes: 4

Views: 6111

Answers (3)

Demodave
Demodave

Reputation: 6632

To test an async method inside of unit test

[TestMethod]
public async Task FunctionName_ActionTaken_ExpectedResult()
{
    await YourFunctionHere();
}

For Mocking Access the from result on the task

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

Upvotes: -2

Vivian River
Vivian River

Reputation: 32380

SomeUser's answer is good, but requires .net 4.6. Since the project I'm working on is .net 4.5, I've had to find something else, and the best thing I've found is:

Task completedTask = Task.Delay(0);

Upvotes: 0

YuvShap
YuvShap

Reputation: 3835

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;

Upvotes: 8

Related Questions