Last Updated: February 25, 2016
·
14.15K
· purekrome

How to unit test an async/await method in .NET

The trick is create a instance of a TaskCompleteSource class. With this instance, you'll be interested in this method & properties:

  • SetResult(...)
  • Task

given the following interface method

public Task<IFtpResult> ftpClient.GetDataAsync() { .. }

and then given the following code that executes this method

IFtpResult ftpResult = await ftpClient.GetDataAsync();

this can be mocked as

var fakeResult = new FtpResult(); // Don't forget to create fake data.
var tcs = new TaskCompletionSource<IFtpResult>();
tcsSetResult(fakeResult);

mockFtpClient
    .Setup(x => x.GetDataAsync())
    .Returns(tcs.Task);

So we first make some fake TaskCompletionSource instance. In that we say When this task were to complete, this is the instance-object I would like to be pretended-to-be-returned.

Then we simply define the mock method and the expected result .. which is a Task that has been faked to return our hardcoded fakeResult.