How to pass in a mocked HttpClient in a .NET test?

后端 未结 4 1773
不思量自难忘°
不思量自难忘° 2020-12-07 17:48

I have a service which uses Microsoft.Net.Http to retrieve some Json data. Great!

Of course, I don\'t want my unit test hitting the actual

4条回答
  •  佛祖请我去吃肉
    2020-12-07 18:17

    I would just make a small change to @Darrel Miller's answer, which is using Task.FromResult to avoid the warning about an async method expecting an await operator.

    public class FakeResponseHandler : DelegatingHandler
    {
        private readonly Dictionary _FakeResponses = new Dictionary();
    
        public void AddFakeResponse(Uri uri, HttpResponseMessage responseMessage)
        {
            _FakeResponses.Add(uri, responseMessage);
        }
    
        protected override Task SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            if (_FakeResponses.ContainsKey(request.RequestUri))
            {
                return Task.FromResult(_FakeResponses[request.RequestUri]);
            }
            else
            {
                return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound) { RequestMessage = request });
            }
        }
    }
    

提交回复
热议问题