4km_eg
Last Updated: February 25, 2016
·
6.351K
· purekrome
566e902e083f0bc679019be97a39344e

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.

Say Thanks
Respond