title: Mocking HttpClient GetAsync by using Moq library in Xunit test
body: <p>I am writing a simple unit test for this small service that simply calls external APIs:</p>
  
  <pre><code>public class ApiCaller : IApiCaller
  {
      private readonly IHttpClientFactory _httpFactory;
  
      public ApiCaller(IHttpClientFactory httpFactory)
      {
          _httpFactory = httpFactory;
      }
  
      public async Task&lt;T&gt; GetResponseAsync&lt;T&gt;(Uri url)
      {
          using (HttpClient client = _httpFactory.CreateClient())
          {
              client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
              client.Timeout = TimeSpan.FromSeconds(20);
              using (HttpResponseMessage response = await client.GetAsync(url))
              {
                  response.EnsureSuccessStatusCode();
                  string responseBody = await response.Content.ReadAsStringAsync();
  
                  return JsonConvert.DeserializeObject&lt;T&gt;(responseBody);
              }
  
          }
      }
  }
  </code></pre>
  
  <p>My first question is: it doesn't seem to be very common practice mocking and therefore testing such services and I am wondering if there is some specific explanation.</p>
  
  <p>Second, I tried to write a simple unit test but I cannot Mock the <strong>GetAsync</strong> call since HttpClient doesn't implement any interface.</p>
  
  <pre><code>public class ApiCallerTest
  {
      private readonly ApiCaller _target;
      private readonly Mock&lt;IHttpClientFactory&gt; _httpClientFactory;
  
  
      public ApiCallerTest()
      {
          _httpClientFactory = new Mock&lt;IHttpClientFactory&gt;();
          _target = new ApiCaller(_httpClientFactory.Object);
      }
  
      [Fact]
      public void WhenACorrectUrlIsProvided_ServiceShouldReturn()
      {
  
  
          var client = new HttpClient();
          _httpClientFactory.Setup(x =&gt; x.CreateClient(It.IsAny&lt;string&gt;())).Returns(client);
  
          var httpMessageHandler = new Mock&lt;HttpMessageHandler&gt;();
  
      }
  
  }
  </code></pre>