Introduction
This article explains how to mock the HttpClient using XUnit. Yes, we already have few ways to mock httpclient by writing a wrapper for HttpClient. But there is a problem for not covering test cases for HttpClient class, since we know there isn't an interface inherited with HttpClient. To handle this case, we introduced HttpClient property in the interface. Using this interface property we can achieve whatever we want around httpclient mocking.
Problem Statement
As I already mentioned, HttpClient does not inherit from any interface, so you will have to write your own. A few of them suggest a decorator-like pattern.
So, here we are mocking only wrapper class and not httpclient. So how can we mock httpclient as well? Let's see it in action, I am using Visual Studio 2019, .Net Core 2.0, and XUnit.
Step 1
To demonstrate httpclient mocking using Xunit, I am creating a simple web API application and adding a new test(XUnit) project.

Step 2
Let's introduce IHttpClientHelper interface to mock httpclient. Here you can see HttpClient property as well, which is used to hold the mocked HttpMessageHandler object.

The implementation class for IHttpClientHelper looks like below:
- using System;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Threading.Tasks;
- namespace Demo.Services
- {
- public class HttpClientHelper : IHttpClientHelper
- {
- public HttpClient HttpClient { get; set; }
- public async Task<TResult> GetAsync<TResult>(string requestUri)
- {
- TResult objResult = default(TResult);
- using (var client = this.GetHttpClient())
- {
- using (var response = await client.GetAsync(requestUri))
- {
- if (TryParse<TResult>(response, out objResult))
- {
- return objResult;
- }
- using (HttpContent content = response.Content)
- {
- throw new HttpRequestException(response.Content.ReadAsStringAsync().Result);
- }
- }
- }
- }
- private HttpClient GetHttpClient()
- {
- if (HttpClient == null)//While mocking we set httpclient object to bypass actual result.
- {
- var _httpClient = new HttpClient();
- _httpClient.DefaultRequestHeaders.Accept.Clear();
- _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- return _httpClient;
- }
- return HttpClient;
- }
- private bool TryParse<TResult>(HttpResponseMessage response, out TResult t)
- {
- if (typeof(TResult).IsAssignableFrom(typeof(HttpResponseMessage)))
- {
- t = (TResult)Convert.ChangeType(response, typeof(TResult));
- return true;
- }
- if (response.IsSuccessStatusCode)
- {
- t = response.Content.ReadAsAsync<TResult>().Result;
- return true;
- }
- t = default(TResult);
- return false;
- }
- }
- }



Bhavesh Ramburn BSc (hons), LLM, MCIArbPosted Jul 30, 2022, 7:51 PM
Thanks mate I was looking for a solution to this.