title: How to Unit Test Exception Handler Middleware
body: <p>I am trying to use a custom error handler to return properly formatted exceptions for my .NET Core 3 API. The handler works great, the issue I'm having is with regards to writing proper unit tests to test the handler. I registered the middleware for this like so:</p>
  
  <pre><code>    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IEnvService envService)
      {
          if (envService.IsNonProductionEnv())
          {
              app.UseExceptionHandler("/Error-descriptive");
          }
          else
          {
              app.UseExceptionHandler("/Error");
          }
  
          ...
  
       }
  </code></pre>
  
  <p>Here is the code for the 'Error Descriptive' endpoint:</p>
  
  <pre><code>    public IActionResult ErrorDescriptive()
      {
          if (!_env.IsNonProductionEnv())            
              throw new InvalidOperationException("This endpoint cannot be invoked in a production environment.");
  
          IExceptionHandlerFeature exFeature = HttpContext.Features.Get&lt;IExceptionHandlerFeature&gt;();
  
          return Problem(detail: exFeature.Error.StackTrace, title: exFeature.Error.Message);
       }
  </code></pre>
  
  <p>The issue I'm dealing with specifically is this line:</p>
  
  <pre><code>IExceptionHandlerFeature exFeature = HttpContext.Features.Get&lt;IExceptionHandlerFeature&gt;();
  </code></pre>
  
  <p>I'm having trouble getting this to work from a unit testing perspective, because (as far as I know) this line of code gets the most recent exception from the server. Is there a way I can somehow set the exception it gets from the HttpContext within my test? Also, since this is using HttpContext, do I somehow need to incorporate a mocked version of that as well, such as DefaultHttpContext? </p>