public async Task Invoke_HandlerAdded_HandlerCalled(NullLoggerFactory loggerFactory, Mock <IServiceProvider> serviceProviderMock, string exceptionMessage, int statusCode, string path, string method) { var expectedResponse = new TestResponse { Message = exceptionMessage }; var exceptionHandler = new Mock <IExceptionHandler <ArgumentException> >(); exceptionHandler .Setup(eh => eh.GetResponseData(It.IsAny <Exception>(), It.IsAny <ResponseContext>())) .Returns((Exception exc, ResponseContext opt) => new ResponseData { StatusCode = statusCode, Body = expectedResponse }); serviceProviderMock .Setup(s => s.GetService(typeof(IExceptionHandler <ArgumentException>))) .Returns(exceptionHandler.Object); //Arrange var requestDelegate = new RequestDelegate(httpContext => throw new ArgumentException(exceptionMessage)); var httpContextMock = new HttpContextMock(); httpContextMock.HttpResponseMock.SetupSet(m => m.StatusCode = statusCode).Verifiable(); var expectedBody = JObject.FromObject(expectedResponse); httpContextMock.HttpRequestMock.SetupGet(r => r.Path).Returns("/" + path); httpContextMock.HttpRequestMock.SetupGet(r => r.Method).Returns(method); var middleware = new ExceptionMiddleware(requestDelegate, loggerFactory, serviceProviderMock.Object); //Act await middleware.Invoke(httpContextMock.Object); //Assert httpContextMock.HttpResponseMock.Verify(); JToken.DeepEquals(expectedBody, JObject.Parse(httpContextMock.HttpResponseMock.ActualBody)); }