title: Mocked HttpClientFactory returns null when creating client
body: <p>I am trying to unit test a service that uses the <code>IHttpClientFactory</code> with Nunit and NSubstitute for mocking. </p>
  
  <p>The service I want to test looks like this     </p>
  
  <pre><code>public class Movies : IMovies
  {
      private readonly IHttpClientFactory _httpClientFactory;
  
      public Movies(IHttpClientFactory httpClientFactory)
      { 
          _httpClientFactory = httpClientFactory;
      }
  
      public async Task&lt;MovieCollection&gt; GetPopularMovies(int PageNumber = 1)
      {
  
          // Get an instance of HttpClient from the factpry that we registered
          // in Startup.cs
           var client = _httpClientFactory.CreateClient("Movie Api");
  
          // Call the API &amp; wait for response. 
          // If the API call fails, call it again according to the re-try policy
          // specified in Startup.cs
          var result =
              await client.GetAsync($"movie/popular?api_key=&lt;the_api_key&gt;language=en-US&amp;page={PageNumber}");
          if (result.IsSuccessStatusCode)
          {
              // Read all of the response and deserialise it into an instace of
  
              var content = await result.Content.ReadAsStringAsync();
              return JsonConvert.DeserializeObject&lt;MovieCollection&gt;(content);
          }
  
          return null;
      }
  }
  </code></pre>
  
  <p>When I run the test I get an error that says</p>
  
  <blockquote>
    <p>System.NullReferenceException : Object reference not set to an instance of an object.
         at MovieApi.Services.Movies.GetPopularMovies(Int...</p>
  </blockquote>
  
  <p>Here is the test I am running.The error occurs only when I put the keyword <code>await</code> in the line</p>
  
  <pre><code>var result = await service.GetPopularMovies(1);
  </code></pre>
  
  <p>Check the Test code below:</p>
  
  <pre><code>[Test]
  public async Task GetPopular_WhenCalled_ReturnOK()
  {
  
    //arrange
    var moviecollection = new MovieCollection();
    var httpClientFactoryMock = Substitute.For&lt;IHttpClientFactory&gt;();
  
    var fakeHttpMessageHandler = new FakeHttpMessageHandler(new HttpResponseMessage() {
      StatusCode = HttpStatusCode.OK,
      Content = new StringContent(JsonConvert.SerializeObject(moviecollection), Encoding.UTF8, "application/json") 
    });
    var fakeHttpClient = new HttpClient(fakeHttpMessageHandler);
  
    httpClientFactoryMock.CreateClient().Returns(fakeHttpClient);
  
    // Act
    var service = new Movies(httpClientFactoryMock);
    var result = await service.GetPopularMovies(1);
    //assert
    Assert.IsNotNull(result);
  }
  </code></pre>