|
| 1 | +using ExceptionHandlingExtension.Tests.Infrastructure.Extensions; |
| 2 | +using FluentAssertions; |
| 3 | +using Microsoft.AspNetCore.Builder; |
| 4 | +using Microsoft.AspNetCore.Hosting; |
| 5 | +using Microsoft.AspNetCore.TestHost; |
| 6 | +using Microsoft.Extensions.DependencyInjection; |
| 7 | +using Microsoft.Extensions.Hosting; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using Moq; |
| 10 | +using System.Text.Json; |
| 11 | +using TechBuddy.Extensions.AspNetCore.ExceptionHandling; |
| 12 | +using TechBuddy.Extensions.AspNetCore.ExceptionHandling.Infrastructure.Models; |
| 13 | +using TechBuddy.Extensions.Tests.Common.TestCommon.Constants; |
| 14 | + |
| 15 | +namespace ExceptionHandlingExtension.Tests; |
| 16 | +public sealed class ExceptionHandlingTests |
| 17 | +{ |
| 18 | + [Test] |
| 19 | + public async Task ExceptionHandlingWithNoHandler_WithNoDetails_ShouldReturnInternalServerError() |
| 20 | + { |
| 21 | + // Arrange |
| 22 | + var server = GetServerWithOptions(new ExceptionHandlingOptions()); |
| 23 | + var client = server.CreateClient(); |
| 24 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowException"); |
| 25 | + |
| 26 | + // Action |
| 27 | + HttpResponseMessage response = await client.SendAsync(request); |
| 28 | + |
| 29 | + // Assert |
| 30 | + response.IsSuccessStatusCode.Should().BeFalse(); |
| 31 | + response.StatusCode.Should().Be(System.Net.HttpStatusCode.InternalServerError); |
| 32 | + } |
| 33 | + |
| 34 | + [Test] |
| 35 | + public async Task ExceptionHandlingWithNoHandler_WhenUseExceptionDetailsIsFalse_ShouldReturnInternalServerErrorMessage() |
| 36 | + { |
| 37 | + // Arrange |
| 38 | + var server = GetServerWithOptions(new ExceptionHandlingOptions()); |
| 39 | + var client = server.CreateClient(); |
| 40 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowException"); |
| 41 | + |
| 42 | + // Action |
| 43 | + HttpResponseMessage response = await client.SendAsync(request); |
| 44 | + var responseContent = await response.Content.ReadAsStringAsync(); |
| 45 | + |
| 46 | + // Assert |
| 47 | + var resObj = JsonSerializer.Deserialize<DefaultExceptionHandlerResponseModel>(responseContent, GeneralConstants.JsonOptions); |
| 48 | + |
| 49 | + resObj.Should().NotBeNull(); |
| 50 | + resObj.Detail.Should().Be(TestConstants.DefaultExceptionMessage); |
| 51 | + } |
| 52 | + |
| 53 | + [Test] |
| 54 | + public async Task ExceptionHandlingWithNoHandler_WhenUseExceptionDetailsIsTrue_ShouldReturnExceptionMessage() |
| 55 | + { |
| 56 | + // Arrange |
| 57 | + var options = new ExceptionHandlingOptions(); |
| 58 | + options.UseLogger(true); |
| 59 | + var server = GetServerWithOptions(options); |
| 60 | + var client = server.CreateClient(); |
| 61 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowException"); |
| 62 | + |
| 63 | + // Action |
| 64 | + HttpResponseMessage response = await client.SendAsync(request); |
| 65 | + var responseContent = await response.Content.ReadAsStringAsync(); |
| 66 | + |
| 67 | + |
| 68 | + // Assert |
| 69 | + var resObj = JsonSerializer.Deserialize<DefaultExceptionHandlerResponseModel>(responseContent, GeneralConstants.JsonOptions); |
| 70 | + |
| 71 | + resObj.Should().NotBeNull(); |
| 72 | + resObj.Detail.Should().Contain(TestConstants.ExceptionMessage); |
| 73 | + } |
| 74 | + |
| 75 | + [Test] |
| 76 | + public async Task ExceptionHandlingWithNoHandler_WithDetails_ShouldReturnInternalServer() |
| 77 | + { |
| 78 | + // Arrange |
| 79 | + var options = new ExceptionHandlingOptions(); |
| 80 | + options.UseLogger(true); |
| 81 | + var server = GetServerWithOptions(options); |
| 82 | + var client = server.CreateClient(); |
| 83 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowException"); |
| 84 | + |
| 85 | + // Action |
| 86 | + HttpResponseMessage response = await client.SendAsync(request); |
| 87 | + |
| 88 | + |
| 89 | + // Assert |
| 90 | + response.IsSuccessStatusCode.Should().BeFalse(); |
| 91 | + response.StatusCode.Should().Be(System.Net.HttpStatusCode.InternalServerError); |
| 92 | + } |
| 93 | + |
| 94 | + [Test] |
| 95 | + public async Task ExceptionHandlingWithNoHandler_WithDetails_ShouldReturnExceptionMessage() |
| 96 | + { |
| 97 | + // Arrange |
| 98 | + var options = new ExceptionHandlingOptions(); |
| 99 | + options.UseLogger(true); |
| 100 | + var server = GetServerWithOptions(options); |
| 101 | + var client = server.CreateClient(); |
| 102 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowException"); |
| 103 | + |
| 104 | + // Action |
| 105 | + HttpResponseMessage response = await client.SendAsync(request); |
| 106 | + var responseContent = await response.Content.ReadAsStringAsync(); |
| 107 | + |
| 108 | + // Assert |
| 109 | + response.IsSuccessStatusCode.Should().BeFalse(); |
| 110 | + response.StatusCode.Should().Be(System.Net.HttpStatusCode.InternalServerError); |
| 111 | + |
| 112 | + var resObj = JsonSerializer.Deserialize<DefaultExceptionHandlerResponseModel>(responseContent, GeneralConstants.JsonOptions); |
| 113 | + |
| 114 | + resObj.Should().NotBeNull(); |
| 115 | + resObj.Detail.Should().StartWith($"System.Exception: {TestConstants.ExceptionMessage}"); |
| 116 | + } |
| 117 | + |
| 118 | + [Test] |
| 119 | + public async Task ExceptionHandling_WithHandler_ShouldReturnExceptionMessage() |
| 120 | + { |
| 121 | + // Arrange && Assert |
| 122 | + var opt = new ExceptionHandlingOptions(); |
| 123 | + opt.UseCustomHandler(async (ctx, ex, logger) => |
| 124 | + { |
| 125 | + ex.Message.Should().NotBeNull(); |
| 126 | + ex.Message.Should().Be(TestConstants.ExceptionMessage); |
| 127 | + |
| 128 | + await Task.CompletedTask; // expects returning task |
| 129 | + }); |
| 130 | + |
| 131 | + var server = GetServerWithOptions(opt); |
| 132 | + var client = server.CreateClient(); |
| 133 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowException"); |
| 134 | + |
| 135 | + // Action |
| 136 | + HttpResponseMessage response = await client.SendAsync(request); |
| 137 | + } |
| 138 | + |
| 139 | + |
| 140 | + [Test] |
| 141 | + public async Task ExceptionHandlingWithHandler_WhenWriteToResponse_ShouldReturnTheMessage() |
| 142 | + { |
| 143 | + // Arrange && Assert |
| 144 | + var opt = new ExceptionHandlingOptions(); |
| 145 | + opt.UseCustomHandler(async (ctx, ex, logger) => |
| 146 | + { |
| 147 | + ex.Message.Should().NotBeNull(); |
| 148 | + ex.Message.Should().Be(TestConstants.ExceptionMessage); |
| 149 | + |
| 150 | + // writes as json, so it's like "TestConstants.ExceptionMessage" |
| 151 | + await ctx.WriteResponseAsync(TestConstants.ExceptionMessage, System.Net.HttpStatusCode.InternalServerError); |
| 152 | + }); |
| 153 | + |
| 154 | + var server = GetServerWithOptions(opt); |
| 155 | + var client = server.CreateClient(); |
| 156 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowException"); |
| 157 | + |
| 158 | + // Action |
| 159 | + HttpResponseMessage response = await client.SendAsync(request); |
| 160 | + var responseContent = await response.Content.ReadAsStringAsync(); |
| 161 | + |
| 162 | + // Assert |
| 163 | + response.StatusCode.Should().Be(System.Net.HttpStatusCode.InternalServerError); |
| 164 | + responseContent.Should().Be($"\"{TestConstants.ExceptionMessage}\""); |
| 165 | + } |
| 166 | + |
| 167 | + |
| 168 | + [Test] |
| 169 | + public async Task ExceptionHandlingWithNoHandler_WithCustomLogger_ShouldCallLogError() |
| 170 | + { |
| 171 | + // Arrange |
| 172 | + Mock<ILogger> mockLogger = new Mock<ILogger>(); |
| 173 | + var opt = new ExceptionHandlingOptions(); |
| 174 | + opt.UseLogger(mockLogger.Object); |
| 175 | + var server = GetServerWithOptions(opt); |
| 176 | + var client = server.CreateClient(); |
| 177 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowException"); |
| 178 | + |
| 179 | + // Action |
| 180 | + HttpResponseMessage response = await client.SendAsync(request); |
| 181 | + |
| 182 | + // Assert |
| 183 | + mockLogger.Verify(m => m.Log(LogLevel.Error, |
| 184 | + It.IsAny<EventId>(), |
| 185 | + It.Is<It.IsAnyType>((v, t) => true), |
| 186 | + It.IsAny<Exception>(), |
| 187 | + It.IsAny<Func<It.IsAnyType, Exception, string>>()), Times.Once); |
| 188 | + } |
| 189 | + |
| 190 | + [Test] |
| 191 | + public async Task ExceptionHandlingWithNoHandler_WithCustomLogger_ShouldCallLogErrorWithMessageDetails() |
| 192 | + { |
| 193 | + // Arrange |
| 194 | + var expectedMessage = TestConstants.ExceptionMessage; |
| 195 | + Mock<ILogger> mockLogger = new Mock<ILogger>(); |
| 196 | + var opt = new ExceptionHandlingOptions(); |
| 197 | + opt.UseLogger(mockLogger.Object, true); |
| 198 | + var server = GetServerWithOptions(opt); |
| 199 | + var client = server.CreateClient(); |
| 200 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowException"); |
| 201 | + |
| 202 | + // Action |
| 203 | + HttpResponseMessage response = await client.SendAsync(request); |
| 204 | + |
| 205 | + // Assert |
| 206 | + mockLogger.Verify(logger => logger.Log(LogLevel.Error, |
| 207 | + It.IsAny<EventId>(), |
| 208 | + It.Is<It.IsAnyType>((v, _) => v.ToString().Contains(expectedMessage)), |
| 209 | + It.IsAny<Exception>(), |
| 210 | + (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), |
| 211 | + Times.Once); |
| 212 | + } |
| 213 | + |
| 214 | + [Test] |
| 215 | + public async Task ExceptionHandling_WithSingleCustomHandler_ShouldBeCalled() |
| 216 | + { |
| 217 | + // Assert |
| 218 | + var functionWasInvoked = false; |
| 219 | + var expectedMessage = TestConstants.ExceptionMessage; |
| 220 | + var options = new ExceptionHandlingOptions(); |
| 221 | + options.UseLogger(true); |
| 222 | + |
| 223 | + options.AddCustomHandler<Exception>((context, ex, logger) => |
| 224 | + { |
| 225 | + functionWasInvoked = true; |
| 226 | + ex.Message.Should().Be(expectedMessage); |
| 227 | + return Task.CompletedTask; |
| 228 | + }); |
| 229 | + |
| 230 | + var server = GetServerWithOptions(options); |
| 231 | + var client = server.CreateClient(); |
| 232 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowException"); |
| 233 | + |
| 234 | + // Action |
| 235 | + HttpResponseMessage response = await client.SendAsync(request); |
| 236 | + |
| 237 | + // Assert |
| 238 | + functionWasInvoked.Should().BeTrue(); |
| 239 | + } |
| 240 | + |
| 241 | + [Test] |
| 242 | + public async Task ExceptionHandlingWithCustomHandler_WithUseHandler_ShouldBeCalled() |
| 243 | + { |
| 244 | + // Assert |
| 245 | + bool functionWasInvoked = false; |
| 246 | + var options = new ExceptionHandlingOptions(); |
| 247 | + |
| 248 | + options.UseCustomHandler((context, ex, logger) => |
| 249 | + { |
| 250 | + functionWasInvoked = false; |
| 251 | + return Task.CompletedTask; |
| 252 | + }); |
| 253 | + |
| 254 | + options.AddCustomHandler<InvalidOperationException>((context, ex, logger) => |
| 255 | + { |
| 256 | + functionWasInvoked = true; |
| 257 | + return Task.CompletedTask; |
| 258 | + }); |
| 259 | + |
| 260 | + var server = GetServerWithOptions(options); |
| 261 | + var client = server.CreateClient(); |
| 262 | + var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Test/ThrowCustomException"); |
| 263 | + |
| 264 | + // Action |
| 265 | + HttpResponseMessage response = await client.SendAsync(request); |
| 266 | + |
| 267 | + // Assert |
| 268 | + functionWasInvoked.Should().BeTrue(); |
| 269 | + } |
| 270 | + |
| 271 | + #region Private Methods |
| 272 | + |
| 273 | + private static TestServer GetServerWithOptions(ExceptionHandlingOptions options) |
| 274 | + { |
| 275 | + var hostBuilder = new WebHostBuilder() |
| 276 | + .ConfigureServices(services => |
| 277 | + { |
| 278 | + services.AddMvc(i => i.EnableEndpointRouting = false); |
| 279 | + }) |
| 280 | + .Configure(async (app) => |
| 281 | + { |
| 282 | + var env = app.ApplicationServices.GetService<IWebHostEnvironment>(); |
| 283 | + |
| 284 | + await app.ConfigureTechBuddyExceptionHandling(options); |
| 285 | + |
| 286 | + app.UseMvc(); |
| 287 | + }); |
| 288 | + |
| 289 | + return new TestServer(hostBuilder); |
| 290 | + } |
| 291 | + |
| 292 | + #endregion |
| 293 | +} |
0 commit comments