-
Notifications
You must be signed in to change notification settings - Fork 516
Expand file tree
/
Copy pathExceptionMiddlewareTests.cs
More file actions
67 lines (54 loc) · 2.11 KB
/
ExceptionMiddlewareTests.cs
File metadata and controls
67 lines (54 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
namespace EvolutionaryArchitecture.Fitnet.Common.Api.UnitTests;
using ErrorHandling;
using Core.BusinessRules;
using System.IO;
using System.Threading.Tasks;
using System;
public sealed class ExceptionMiddlewareTests
{
private readonly HttpContext _context = GetHttpContext();
[Fact]
internal async Task Given_business_rule_validation_exception_Then_returns_conflict()
{
// Arrange
const string exceptionMessage = "Business rule not met";
var middleware =
new ExceptionMiddleware(context => throw new BusinessRuleValidationException(exceptionMessage));
// Act
await middleware.InvokeAsync(_context);
// Assert
_context.Response.StatusCode.ShouldBe((int)HttpStatusCode.Conflict);
var responseMessage = await GetExceptionResponseMessage();
responseMessage.ShouldBe(exceptionMessage);
}
[Fact]
internal async Task Given_other_than_business_rule_validation_exception_Then_returns_internal_server_error()
{
// Arrange
const string exceptionMessage = "Some exception";
var middleware =
new ExceptionMiddleware(context => throw new InvalidOperationException(exceptionMessage));
// Act
await middleware.InvokeAsync(_context);
// Assert
_context.Response.StatusCode.ShouldBe((int)HttpStatusCode.InternalServerError);
var responseMessage = await GetExceptionResponseMessage();
responseMessage.ShouldBe(exceptionMessage);
}
private static DefaultHttpContext GetHttpContext() =>
new()
{
Response =
{
Body = new MemoryStream()
}
};
private async Task<string> GetExceptionResponseMessage()
{
_context.Response.Body.Seek(0, SeekOrigin.Begin);
using var streamReader = new StreamReader(_context.Response.Body);
var responseBody = await streamReader.ReadToEndAsync();
var responseContent = JsonConvert.DeserializeObject<dynamic>(responseBody);
return responseContent != null ? (string)responseContent.Message : string.Empty;
}
}