Using Moq to mock an asynchronous method for a unit test

前端 未结 3 901
北海茫月
北海茫月 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<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.

    0 讨论(0)
  • 2020-11-30 19:27

    With Mock.Of<...>(...) for async method you can use Task.FromResult(...):

    var client = Mock.Of<IHttpClient>(c => 
        c.PostAsync(It.IsAny<Uri>(), It.IsAny<HttpContent>()) == Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK))
    );
    
    0 讨论(0)
  • 2020-11-30 19:31

    Recommend @Stuart Grassie's answer above.

    var moqCredentialMananger = new Mock<ICredentialManager>();
    moqCredentialMananger
                        .Setup(x => x.GetCredentialsAsync(It.IsAny<string>()))
                        .ReturnsAsync(new Credentials() { .. .. .. });
    
    0 讨论(0)
提交回复
热议问题