コード例 #1
0
        public async Task ErrorWrapping_Middleware_Should_Return_Error()
        {
            var exceptionHandler = new ErrorWrappingMiddleware((innerHttpContext) =>
            {
                throw new Exception("Test exception");
            }, new NullLogger <ErrorWrappingMiddleware>());

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream(); // <== Replace the NullStream

            await exceptionHandler.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader = new StreamReader(context.Response.Body);
            var text   = reader.ReadToEnd();

            Assert.False(string.IsNullOrEmpty(text));
        }
コード例 #2
0
        public async Task GetTableAsync_AccessMethodThrowsError_LogEventOccursAndErrorStatusCodeReturnedNoExceptionThrown()
        {
            // Arrange
            var exceptionToThrow = new Exception("exception");
            var apiQueryModel    = new ApiQueryModel();

            _dbViewAccess.Setup(x => x.GetTableAsync(apiQueryModel))
            .ThrowsAsync(exceptionToThrow);

            Db2DbViewController controller = new Db2DbViewController(_dbViewAccess.Object);

            // Set up our Error Handling middleware as a wrapper (the same way it will wrap all incoming Requests)
            var middleware = new ErrorWrappingMiddleware(async(innerHttpContext) =>
            {
                var result = await controller.GetTableAsync(apiQueryModel);
            }, _logger.Object);

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            //Act
            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader      = new StreamReader(context.Response.Body);
            var streamText  = reader.ReadToEnd();
            var objResponse = JsonConvert.DeserializeObject <ApiResponse>(streamText);

            //Assert
            _logger.Verify(x =>
                           x.LogError(exceptionToThrow, It.IsAny <string>()), Times.Once);

            objResponse
            .Should()
            .BeEquivalentTo(new ApiResponse(HttpStatusCode.InternalServerError, "exception"));

            context.Response.StatusCode
            .Should()
            .Be((int)HttpStatusCode.InternalServerError);
        }