Home » c# » c# – How to Unit Test Exception Handler Middleware-Exceptionshub

c# – How to Unit Test Exception Handler Middleware-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

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:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IEnvService envService)
    {
        if (envService.IsNonProductionEnv())
        {
            app.UseExceptionHandler("/Error-descriptive");
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }

        ...

     }

Here is the code for the ‘Error Descriptive’ endpoint:

    public IActionResult ErrorDescriptive()
    {
        if (!_env.IsNonProductionEnv())            
            throw new InvalidOperationException("This endpoint cannot be invoked in a production environment.");

        IExceptionHandlerFeature exFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();

        return Problem(detail: exFeature.Error.StackTrace, title: exFeature.Error.Message);
     }

The issue I’m dealing with specifically is this line:

IExceptionHandlerFeature exFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();

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?

How to&Answers: