Using Moq to mock an asynchronous method for a unit test

You’re creating a task but never starting it, so it’s never completing. However, don’t just start the task – instead, change to using Task.FromResult<TResult> which will give you a task which has already completed:

...
.Returns(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)));

Note that you won’t be testing the actual asynchrony this way – if you want to do that, you need to do a bit more work to create a Task<T> that you can control in a more fine-grained manner… but that’s something for another day.

You might also want to consider using a fake for IHttpClient rather than mocking everything – it really depends on how often you need it.

Leave a Comment