title: Using asp.net 5 TestServer to Mock an external Api call
body: <p>I am trying to use <a href="https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.TestHost/TestServer.cs" rel="nofollow">TestServer</a> to test my middleware. 
  Somewhere in the middleware, my code is calling an api through HttpClient. I would like to mock this by using a second TestServer but wonder if this is possible. I already tried, but I have the error : <em>"Trying to connect ... but the server actively refused it."</em></p>
  
  <p>here is how the code could look like : </p>
  
  <pre><code>  [Fact]
      public async Task Should_give_200_Response()
      {
          var server = TestServer.Create((app) =&gt; 
          {
              app.UseMiddleware&lt;DummyMiddleware&gt;();
          });
          var fakeServer = TestServer.Create((app) =&gt; 
          {
              app.UseMiddleware&lt;FakeMiddleware&gt;();
          });
  
          using(server)
          {
            using(fakeServer)
            { 
              var response = await server.CreateClient().GetAsync("/somePath");
              Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }
          }
      }
  </code></pre>
  
  <p>Somewhere in the code of DummyMiddleware, I am doing an </p>
  
  <pre><code> HttpClient client = new HttpClient() { BaseAddress = "http://fakeUrl.com"};
   var resp = client.GetAsync("/path/to/api");
  </code></pre>
  
  <p>the url : <a href="http://fakeUrl.com" rel="nofollow">http://fakeUrl.com</a> would be mocked by the fakeServer. but in fact a real call to <a href="http://fakeUrl" rel="nofollow">http://fakeUrl</a> is issued over the network, but I would like it to hit the fakeserver so that I could mock that api.</p>
  
  <p>Imagine that the fakeserver would mock google calendar api for instance.</p>
  
  <p><strong>Update</strong> : Use of fakeServer
  In fact the fakeServer would listen to this url : "<a href="http://fakeUrl.com" rel="nofollow">http://fakeUrl.com</a>" and when receive the route "/path/to/api" it would return a json object for instance. What I would like to, is my fakeServer to be returned a mocked object. as a reminder,  "<a href="http://fakeUrl.com/path/to/api" rel="nofollow">http://fakeUrl.com/path/to/api</a>" would be called somewhere in my code with an HttpClient object.</p>