title: Mock HttpClient using Moq
body: <p>I would like to unit test a class that uses <code>HttpClient</code>. We injected the <code>HttpClient</code> object in the class constructor.</p>
  <pre><code>public class ClassA : IClassA
  {
      private readonly HttpClient _httpClient;
  
      public ClassA(HttpClient httpClient)
      {
          _httpClient = httpClient;
      }
  
      public async Task&lt;HttpResponseMessage&gt; SendRequest(SomeObject someObject)
      {
          //Do some stuff
  
          var request = new HttpRequestMessage(HttpMethod.Post, &quot;http://some-domain.in&quot;);
  
          //Build the request
  
          var response = await _httpClient.SendAsync(request);
  
          return response;
      }
  }
  </code></pre>
  <p>Now we would like to unit test the <code>ClassA.SendRequest</code> method. We are using <code>Ms Test</code> for unit testing framework and <code>Moq</code> for mocking.</p>
  <p>When we tried to mock the <code>HttpClient</code>, it throws <code>NotSupportedException</code>.</p>
  <pre><code>[TestMethod]
  public async Task SendRequestAsync_Test()
  {
      var mockHttpClient = new Mock&lt;HttpClient&gt;();
  
      mockHttpClient.Setup(
          m =&gt; m.SendAsync(It.IsAny&lt;HttpRequestMessage&gt;()))
      .Returns(() =&gt; Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
  }
  </code></pre>
  <p>How can we solve this issue?</p>