4

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.

Community
  • 1
  • 1
Vivian River
  • 31,198
  • 62
  • 198
  • 313
  • 1
    What do you need the `Task` to do? There are all sorts of ways for you to create tasks that do all sorts of things, and have all sorts of properties, but without knowing what properties you want your `Task` to have, we couldn't possibly know how to implement it. – Servy Nov 15 '16 at 20:24

3 Answers3

8

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;
YuvShap
  • 3,825
  • 2
  • 10
  • 24
0

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);
Vivian River
  • 31,198
  • 62
  • 198
  • 313
-2

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);
Demodave
  • 6,242
  • 6
  • 43
  • 58
  • You have misunderstood the question. The idea here is that `YourFunctionHere` needs to be mocked out to test something that depends on it. I need to tell my mocking framework to substitute a `Task` object for the result without actually invoking it. – Vivian River Nov 15 '16 at 20:30