title: Mock a static HttpClient on Polly's policies using dependency injection in a unit test
body: <p>I have a static HttpClient set up like this:</p>
  
  <pre><code>public class Client
  {
      private static readonly HttpClient _httpClient = new HttpClient()
          ; //WHY? BECAUSE - https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
  
      private static Client instance;
      private static readonly object padlock = new object();
      private Policies policies = new Policies();
  
      public Client(HttpClient httpClient)
      {
          _httpClient = httpClient;
      }
  
      public static Client Instance
      {
          get
          {
              lock (padlock)
              {
                  if (instance != null) return instance;
  
                  instance = new Client();
                  _httpClient.BaseAddress = new Uri("http://whatever.com/v1/");
                  _httpClient.DefaultRequestHeaders.Accept.Clear();
                  _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
                  return instance;
              }
          }
      }
  
      public async Task&lt;string&gt; ExecuteRequest(string request)
      {
          var response = await policies.PolicyWrap.ExecuteAsync(async token =&gt; await _httpClient.PostAsync("", new StringContent(xml)).ConfigureAwait(false), CancellationToken.None);
          if (!response.IsSuccessStatusCode)
              throw new Exception("exception");
  
          return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
      }
  }
  </code></pre>
  
  <p>To call it - <code>Client.Instance.ExecuteRequest("request string here");</code></p>
  
  <p>There is a constructor which can take a mocked Polly's policy and a mocked HttpClient.</p>
  
  <p><code>Policies</code> class looks like this:</p>
  
  <pre><code>public class Policies
  {
      public TimeoutPolicy&lt;HttpResponseMessage&gt; TimeoutPolicy
      {
          get
          {
              return Policy.TimeoutAsync&lt;HttpResponseMessage&gt;(1, onTimeoutAsync: TimeoutDelegate);
          }
      }
      public RetryPolicy&lt;HttpResponseMessage&gt; RetryPolicy
      {
          get
          {
              return Policy.HandleResult&lt;HttpResponseMessage&gt;(r =&gt; !r.IsSuccessStatusCode)
                      .Or&lt;TimeoutRejectedException&gt;()
                      .RetryAsync(3, onRetry: RetryDelegate);
          }
      }
      public FallbackPolicy&lt;HttpResponseMessage&gt; FallbackPolicy
      {
          get
          {
              return Policy.HandleResult&lt;HttpResponseMessage&gt;(r =&gt; !r.IsSuccessStatusCode)
                      .Or&lt;TimeoutRejectedException&gt;()
                      .FallbackAsync(new HttpResponseMessage(HttpStatusCode.InternalServerError), onFallbackAsync: FallbackDelegate);
          }
      }
  
      public PolicyWrap&lt;HttpResponseMessage&gt; PolicyWrap
      {
          get
          {
              return Policy.WrapAsync(FallbackPolicy, RetryPolicy, TimeoutPolicy);
          }
      }
  
      private Task TimeoutDelegate(Context context, TimeSpan timeSpan, Task task)
      {
          //LOG HERE
          return Task.FromResult&lt;object&gt;(null);
      }
  
      private void RetryDelegate(DelegateResult&lt;HttpResponseMessage&gt; delegateResult, int i)
      {
          //LOG HERE
      }
  
      private Task FallbackDelegate(DelegateResult&lt;HttpResponseMessage&gt; delegateResult, Context context)
      {
          //LOG HERE
          return Task.FromResult&lt;object&gt;(null);
      }
  }
  </code></pre>
  
  <p>In a real situation I am only using <code>PolicyWrap</code>.</p>
  
  <p>Policies explanation - after each 1 second timeout retry gets fired. There can be 3 retries after <code>FallbackPolicy</code> gets called.
  In a unit test, I would like to mock an HttpClient so it would timeout (>1 sec Sleep) each time it gets called so 3 timeouts/retries would be fired and a <code>FallbackPolicy</code> would initiate.</p>
  
  <p>The problem here is that the HttpClient is static and I would like it to remain that way so I can not mock it using dependency injection.</p>
  
  <p>So far my test looks like this:</p>
  
  <pre><code>    [TestMethod]
      public async Task HttpClientTest()
      {
          //Arrange
          var fakeResponse = "blabla";
          var httpMessageHandler = new Mock&lt;HttpMessageHandler&gt;();
          httpMessageHandler.Protected()
              .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;("SendAsync", ItExpr.IsAny&lt;HttpRequestMessage&gt;(),
                  ItExpr.IsAny&lt;CancellationToken&gt;())
              .Returns(Task.FromResult(new HttpResponseMessage
              {
                  StatusCode = HttpStatusCode.InternalServerError,//This is where it should fail each time called
                  Content = new StringContent(fakeResponse, Encoding.UTF8, "text/xml")
              }));
  
          var httpClient = new HttpClient(httpMessageHandler.Object);
          httpClient.BaseAddress = new Uri(@"http://some.address.com/v1/");
          httpClient.DefaultRequestHeaders.Accept.Clear();
          httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
  
          IAsyncPolicy&lt;HttpResponseMessage&gt; mockPolicy = Policy.NoOpAsync&lt;HttpResponseMessage&gt;();
  
          var client = new Client(mockPolicy, httpClient);
  
          //Act
          var result = await client.ExecuteRequest("test request"));
  
          //Assert
          Assert.AreEqual("blabla", result.ResponseMessage);
      }
  </code></pre>
  
  <p>Thank you for any input.</p>
  
  <p><strong>EDIT:</strong>
  I have managed to mock the HttpClient from a unit test using dependency injection by just making it non-static and passing the <code>var httpMessageHandler = new Mock&lt;HttpMessageHandler&gt;();</code> into the constructor. (The way I did not want to do, but did not figure out another way)</p>
  
  <p>Retry policy seems to be firing correctly now, however Timeout does not work as expected, transferring my question to: <a href="https://stackoverflow.com/questions/49412806/polly-timeoutpolicy-delegate-not-being-hit-in-an-async-context">Polly TimeoutPolicy delegate not being hit in an async context</a>.</p>