95 lines
3.1 KiB
C#
95 lines
3.1 KiB
C#
using BlazorApp.Middlewares;
|
|
using BlazorApp.Models.Exceptions;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
using Moq;
|
|
using System.Net;
|
|
using System.Text;
|
|
|
|
namespace BlazorApp.Tests.Middlewares
|
|
{
|
|
public class ErrorHandlingMiddlewareTests
|
|
{
|
|
private readonly Mock<ILogger<ErrorHandlingMiddleware>> _loggerMock;
|
|
|
|
public ErrorHandlingMiddlewareTests()
|
|
{
|
|
_loggerMock = new Mock<ILogger<ErrorHandlingMiddleware>>();
|
|
}
|
|
|
|
private HttpContext CreateHttpContext()
|
|
{
|
|
var context = new DefaultHttpContext();
|
|
context.Response.Body = new MemoryStream();
|
|
return context;
|
|
}
|
|
|
|
private string GetResponseBody(HttpContext context)
|
|
{
|
|
context.Response.Body.Seek(0, SeekOrigin.Begin);
|
|
using var reader = new StreamReader(context.Response.Body, Encoding.UTF8);
|
|
return reader.ReadToEnd();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Invoke_WhenNotFoundException_Returns404()
|
|
{
|
|
var context = CreateHttpContext();
|
|
RequestDelegate next = (ctx) => throw new NotFoundException("blabla");
|
|
|
|
var middleware = new ErrorHandlingMiddleware(next, _loggerMock.Object);
|
|
|
|
await middleware.Invoke(context);
|
|
|
|
Assert.Equal((int)HttpStatusCode.NotFound, context.Response.StatusCode);
|
|
var body = GetResponseBody(context);
|
|
Assert.Contains("blabla", body);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Invoke_WhenBusinessException_Returns500()
|
|
{
|
|
var context = CreateHttpContext();
|
|
RequestDelegate next = (ctx) => throw new BusinessException("blabla");
|
|
|
|
var middleware = new ErrorHandlingMiddleware(next, _loggerMock.Object);
|
|
|
|
await middleware.Invoke(context);
|
|
|
|
Assert.Equal((int)HttpStatusCode.InternalServerError, context.Response.StatusCode);
|
|
var body = GetResponseBody(context);
|
|
Assert.Contains("blabla", body);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Invoke_WhenValidationException_Returns400()
|
|
{
|
|
var context = CreateHttpContext();
|
|
RequestDelegate next = (ctx) => throw new ValidationException("blabla");
|
|
|
|
var middleware = new ErrorHandlingMiddleware(next, _loggerMock.Object);
|
|
|
|
await middleware.Invoke(context);
|
|
|
|
Assert.Equal((int)HttpStatusCode.BadRequest, context.Response.StatusCode);
|
|
var body = GetResponseBody(context);
|
|
Assert.Contains("blabla", body);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Invoke_WhenUnhandledException_Returns500()
|
|
{
|
|
var context = CreateHttpContext();
|
|
RequestDelegate next = (ctx) => throw new Exception("blabla");
|
|
|
|
var middleware = new ErrorHandlingMiddleware(next, _loggerMock.Object);
|
|
|
|
await middleware.Invoke(context);
|
|
|
|
Assert.Equal((int)HttpStatusCode.InternalServerError, context.Response.StatusCode);
|
|
var body = GetResponseBody(context);
|
|
Assert.Contains("blabla", body);
|
|
}
|
|
}
|
|
}
|