title: Unit Testing ASP.NET Core HttpResponse.OnStarting()
body: <p>I have an ASP.NET Core middleware which is responsible for adding headers to a response. In following best practices, I am executing the header changes in the context of <code>HttpResponse.OnStarting(Func&lt;Task&gt;)</code>, which ensures callback execution immediately before the response is flushed to the client.</p>
  
  <pre><code>public class ResponseHeadersMiddleware
  {
      private readonly RequestDelegate _next;
  
      public ResponseHeadersMiddleware(RequestDelegate next)
      {
          _next = next;
      }
  
      public async Task Invoke(HttpContext context)
      {
          context.Response.OnStarting(() =&gt;
          {
              context.Response.Headers.Add("X-Some-Header", "Foobar");
  
              return Task.CompletedTask;
          });
  
          // Pass the request through the pipeline 
          await _next(context);
      }
  }
  </code></pre>
  
  <p>This works as-intended, but I am not sure how best to write a unit test for this middleware which actually fires <code>HttpResponse.OnStarting()</code>. The only thing I could come up with was using a <code>Microsoft.AspNetCore.TestHost</code> to build a <code>TestServer</code> which integrates the middleware and executes the full request pipeline. While functional, this is more an integration test, than a true unit test.</p>
  
  <pre><code>[Fact]
  public async Task when_adding_response_headers()
  {
      // ARRANGE
      var subject = new TestServer(new WebHostBuilder()
          .UseStartup&lt;TestStartup&lt;ResponseHeadersMiddleware&gt;&gt;());
  
      // ACT
      var response = await subject.CreateClient()
          .SendAsync(new HttpRequestMessage(HttpMethod.Get, "/")); // middleware fires for all requests
  
      // ASSERT
      Assert.True(response.Headers.TryGetValues("X-Some-Header", out var someHeader));
      Assert.Equals("Foobar", someHeader.FirstOrDefault()
  }
  
  private class TestStartup&lt;TMiddleware&gt; where TMiddleware : class
  {
      public void ConfigureServices(IServiceCollection services)
      {
          RequestDelegate requestDelegate = context =&gt; Task.FromResult(0);
  
          services.AddSingleton(requestDelegate);
          services.AddSingleton&lt;TMiddleware&gt;();
      }
  
      public void Configure(IApplicationBuilder app)
      {
          dynamic middleware = app.ApplicationServices.GetService(typeof(TMiddleware));
  
          app.Use(async (ctx, next) =&gt;
          {
              await middleware.Invoke(ctx);
              await next();
          });
      }
  }
  </code></pre>
  
  <p>Is there a way to trigger <code>HttpResponse.OnStarting()</code> on the HttpContext passed to my middleware, without an end-to-end integration test?</p>