title: How to mock httpMessageHandler with delay?
body: <p>I am constructing an REST API that will call (get) n other REST APIs, concatenate their responses, and then send it to the client.</p>
  
  <p>I am a very worried that my asynchronous method that calls the other services is wrong. I already had a test to it, using moq to mock the answers of the APIs. For days, while I was testing the application and running the tests it was working, then, on the build server, it broke (in the next try, it didn't broke). Obviously, I knew it was a problem with my asynchronous calls. </p>
  
  <p><strong>My goal here is to create a reliable test method that simulates the behavior and the delay of many API calls.</strong></p>
  
  <p>The production code:</p>
  
  <pre><code>private async Task&lt;List&lt;T&gt;&gt; GetInformationFromExternalSource&lt;T&gt;(List&lt;string&gt; urls) where T : BaseDTO
          {
              var response = new List&lt;T&gt;();
              var tasks = new List&lt;Task&lt;List&lt;T&gt;&gt;&gt;();
  
              urls.ForEach(url =&gt;
              {
                  tasks.Add(Task.Run(() =&gt;
                  {
                      string infoJson = RequestDataFromProvider(url).Result;
                      List&lt;T&gt; result = JsonConvert.DeserializeObject&lt;List&lt;T&gt;&gt;(infoJson);
                      return result;
                  }));
              });
  
              await Task.WhenAll(tasks.ToArray());
              tasks.ForEach(t =&gt; response.AddRange(t.Result));
              return response;
          }
  
          private virtual Task&lt;string&gt; RequestDataFromProvider(string url)
          {
              HttpClient client = _clientProvider.getClient();
              var result = client.GetAsync(url).Result;
              return result.Content.ReadAsStringAsync();
          }
  </code></pre>
  
  <p>The test code:</p>
  
  <pre><code>        [Theory]
          [InlineData(3, 2, 5, 7, 17)]
          [InlineData(30, 20, 50, 70, 170)]
          [InlineData(1, 0, 0, 0, 1)]
          [InlineData(43, 1, 0, 0, 44)]
          [InlineData(1, 1, 1, 1, 4)]
          [InlineData(300, 100, 150, 50, 600)]
          [InlineData(0, 0, 0, 0, 0)]
          public async Task GetJsons_WhenHasResponseInManyCalls_ShouldConcatenate(int s1, int s2, int s3, int s4, int expCount)
          {
              //Arrange
              var fakeHttpMessageHandler = new Mock&lt;FakeHttpMessageHandler&gt;(); //here I also tried to use 
              //a SleepyHttpMessageHandler, but I threw a lot of aggregate exceptions because of my Thread.Sleep
              var client = new HttpClient(fakeHttpMessageHandler.Object);
              var providerMock = new Mock&lt;IHttpProvider&gt;();
              providerMock.Setup(f =&gt; f.getClient()).Returns(client);
              var myService = new MyService(providerMock.Object);
  
              //Arrange
              _fakeHttpMessageHandler.SetupSequence(f =&gt; f.Send(It.IsAny&lt;HttpRequestMessage&gt;()))
                  .Returns(httpResponseWithContent(createDummyDto(s1)))
                  .Returns(httpResponseWithContent(createDummyDto(s2)))
                  .Returns(httpResponseWithContent(createDummyDto(s3)))
                  .Returns(httpResponseWithContent(createDummyDto(s4))); //I mocked the DB to have only 4 urls
              //Act
              List&lt;DummyDto&gt; result = await myService.getRequest&lt;DummyDto&gt;(); //getAction will get the urls in database and then return GetInformationFromExternalSource&lt;DummyDto&gt;(urls)
              //Assert
              result.Should().HaveCount(expCount);
          }
  
          private static HttpResponseMessage httpResponseWithContent(List&lt;DummyDto&gt; content1)
          {
              return new HttpResponseMessage
              {
                  StatusCode = HttpStatusCode.OK,
                  Content = new StringContent(JsonConvert.SerializeObject(content1))
              };
          }
  </code></pre>
  
  <p>FakeHttpMessageHandler:</p>
  
  <pre><code>    public class FakeHttpMessageHandler : HttpMessageHandler
      {
          public virtual HttpResponseMessage Send(HttpRequestMessage request)
          {
              throw new NotImplementedException("Now we can setup this method with our mocking framework");
          }
  
          protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
          {
              //Thread.Sleep(100); 
              return Task.FromResult(Send(request));
          }
      }
  </code></pre>
  
  <p>What I want is to wait, for a random time, until the response is sent to the threads.</p>
  
  <p>I have tried <code>setupSequence</code>, <code>callBack</code>, but all of them resulted in more test cases failing than passing.</p>