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.
Written by Pure Krome
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
 #.net 
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#