#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Api.Common.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Nemera.Presentation.Api.UnitTests.Common.Middlewares;
///
/// Contains unit tests for the class.
///
[ExcludeFromCodeCoverage]
public class ExceptionHandlingMiddlewareTests
{
private readonly ILogger _mockLogger;
private readonly ExceptionHandlingMiddleware _sut;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private RequestDelegate _nextDelegate = context => Task.CompletedTask;
///
/// Initializes a new instance of the class.
///
public ExceptionHandlingMiddlewareTests()
{
_mockLogger = Substitute.For>();
_mockLogger.IsEnabled(Arg.Any()).Returns(true);
_sut = new ExceptionHandlingMiddleware(context => _nextDelegate(context), _mockLogger);
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsException_ShouldWriteInternalServerErrorProblemDetails()
{
// Arrange
DefaultHttpContext context = new()
{
Response = { Body = new MemoryStream() }
};
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
// Act
await _sut.InvokeAsync(context);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, context.Response.StatusCode);
Assert.Equal("application/problem+json", context.Response.ContentType);
context.Response.Body.Seek(0, SeekOrigin.Begin);
using StreamReader reader = new(context.Response.Body, Encoding.UTF8);
string responseBody = await reader.ReadToEndAsync();
ProblemDetails problemDetails = JsonSerializer.Deserialize(responseBody, _jsonOptions)!;
Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.6.1", problemDetails.Type);
Assert.Equal("InternalServerError", problemDetails.Title);
Assert.Equal("An unexpected error occurred while processing the request.", problemDetails.Detail);
Assert.False(string.IsNullOrEmpty(problemDetails.Extensions["traceId"]?.ToString()));
Assert.DoesNotContain("sensitive internal details", responseBody);
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsException_ShouldLogTheException()
{
// Arrange
DefaultHttpContext context = new()
{
Response = { Body = new MemoryStream() }
};
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
// Act
await _sut.InvokeAsync(context);
// Assert
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any(),
Arg.Any