public void Invoke_LogsAndRethrows()
        {
            Exception       exception = new Exception();
            ILogger         logger    = Substitute.For <ILogger>();
            HttpContext     context   = Substitute.For <HttpContext>();
            RequestDelegate next      = Substitute.For <RequestDelegate>();

            context.RequestServices.GetService <ILogger>().Returns(logger);
            ExceptionFilterMiddleware middleware = new ExceptionFilterMiddleware(next);

            next.When(sub => sub(context)).Do(info => { throw exception; });

            Exception actual   = Assert.Throws <AggregateException>(() => middleware.Invoke(context).Wait()).InnerException;
            Exception expected = exception;

            logger.Received().Log(exception);
            Assert.Same(expected, actual);
        }
        public async Task InvokeAsync_CatchesExceptionAfterExecutingRequestDelegate()
        {
            // Arrange
            const string exceptionMessage = "InvokeAsync_CatchesExceptionAfterExecutingRequestDelegate";
            var          context          = new DefaultHttpContext();

            _requestDelegate.When(a => a.Invoke(context)).Throw(new NotImplementedException(exceptionMessage));

            // Act
            await _sut.InvokeAsync(context);

            // Assert
            _logger.Received(1).Log(LogLevel.Error, Arg.Any <EventId>(),
                                    Arg.Is <object>(o => o.ToString() == $"An unhandled exception occurred. Trace Identifier: {context.TraceIdentifier}"),
                                    Arg.Is <NotImplementedException>(e => e.Message == exceptionMessage), Arg.Any <Func <object, Exception, string> >());
            context.Response.StatusCode.Should().Be(500);
            context.Response.ContentType.Should().Be("application/json");
            context.Response.Body.Should().NotBeNull();
        }