Using Moq to mock an asynchronous method for a unit test

前端 未结 3 929
北海茫月
北海茫月 2020-11-30 18:44

I am testing a method for a service that makes a Web API call. Using a normal HttpClient works fine for unit tests if I also run the web service (l

3条回答
  •  忘掉有多难
    2020-11-30 19:09

    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 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 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.

提交回复
热议问题