title: How to mock a Stream response when calling HttpClient GetStreamAsync
body: <p>I'm trying to test a class that uses HttpClient and i have to fake the Stream response.</p>
  
  <p>This is the code i'm trying to test.</p>
  
  <pre><code>            try
              {
                  _httpClient.Timeout = TimeSpan.FromMinutes(10);
                  _httpClient.BaseAddress = new Uri(BaseAddress);
                  _httpClient.DefaultRequestHeaders.Accept.Clear();
                  _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                  _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials);
  
                  using (Stream s = _httpClient.GetStreamAsync(API_string).Result)  &lt;---- this is the trouble line.
                  using (StreamReader sr = new StreamReader(s))
                  using (JsonReader reader = new JsonTextReader(sr))
                  {
                      JsonSerializer serializer = new JsonSerializer();
  
                      return serializer.Deserialize&lt;T&gt;(reader); //breaks loop
                  }
              }
  </code></pre>
  
  <p>From the test side, i can insert my custom HttpClientHandler and send back any response i want.</p>
  
  <p>This is my Fake HttpClientHandler builder (I'm using Moq).</p>
  
  <pre><code>    public HttpClientHandler MockHttpClientHandler()
      {
          var requestUri = new Uri("Uri.Expected.To.Be.Called");
          var expectedResponse = "Response text"; &lt;-- This is where i need to write the Object to be returned.
  
          var mockResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(expectedResponse) };
          var mockHandler = new Mock&lt;HttpClientHandler&gt;();
          mockHandler
              .Protected()
              .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(
                  "SendAsync",
                  ItExpr.Is&lt;HttpRequestMessage&gt;(message =&gt; message.RequestUri == requestUri),
                  // ItExpr.IsAny&lt;HttpRequestMessage&gt;(),
                  ItExpr.IsAny&lt;CancellationToken&gt;())
              .Returns(Task.FromResult(mockResponse));
  
          return mockHandler.Object;
      }
  </code></pre>
  
  <p>My test breaks when it tries to run the return line, because whatever i'm sending back can't be deserialized. I just don't know what my Stream s should look like, and i can't see its contents by debugging either.</p>
  
  <p>I'm fairly lost here. Maybe my approach is wrong?</p>
  
  <p>Thanks for any help you can give me.</p>