From 3b7e755499056c9a65d3dca82c65820c128d29c6 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 12 Oct 2024 12:38:31 +0300 Subject: [PATCH] Adds unit tests for UrlStringBinder --- .../Controllers/Common/ApiControllerTests.cs | 284 ++++++++++++++++++ .../Common/Fixtures/ApiControllerFixture.cs | 38 +++ .../Core/ModelBinders/UrlStringBinderTests.cs | 120 ++++++++ 3 files changed, 442 insertions(+) create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/ApiControllerTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/Fixtures/ApiControllerFixture.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/ModelBinders/UrlStringBinderTests.cs diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/ApiControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/ApiControllerTests.cs new file mode 100644 index 00000000..d0946399 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/ApiControllerTests.cs @@ -0,0 +1,284 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Presentation.Api.Common.Http; +using Lumina.Presentation.Api.Core.Controllers.Common; +using Lumina.Presentation.Api.UnitTests.Core.Controllers.Common.Fixtures; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Infrastructure; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ApiControllerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly ApiControllerFixture _sut; + private readonly HttpContext _mockHttpContext; + private readonly ProblemDetailsFactory _mockProblemDetailsFactory; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public ApiControllerTests() + { + _sut = new ApiControllerFixture(); + _mockHttpContext = Substitute.For(); + _mockProblemDetailsFactory = Substitute.For(); + _sut.ControllerContext = new ControllerContext + { + HttpContext = _mockHttpContext + }; + _sut.ProblemDetailsFactory = _mockProblemDetailsFactory; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Problem_WhenCalledWithNoErrors_ShouldReturnGenericProblem() + { + // Arrange + ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); + mockProblemDetailsFactory.CreateProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ProblemDetails()); + + _sut.ProblemDetailsFactory = mockProblemDetailsFactory; + + // Act + IActionResult result = _sut.TestProblem([]); + + // Assert + result.Should().BeOfType(); + ObjectResult objectResult = (ObjectResult)result; + objectResult.Value.Should().BeOfType(); + } + + [Fact] + public void Problem_WhenCalledWithValidationErrors_ShouldReturnValidationProblem() + { + // Arrange + List errors = [ + Error.Validation("Code1", "Description1"), + Error.Validation("Code2", "Description2") + ]; + + _mockProblemDetailsFactory.CreateValidationProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ValidationProblemDetails()); + + // Act + IActionResult result = _sut.TestProblem(errors); + + // Assert + result.Should().BeOfType(); + ObjectResult objectResult = (ObjectResult)result; + objectResult.Value.Should().BeOfType(); + } + + [Theory] + [InlineData(ErrorType.Conflict, StatusCodes.Status409Conflict)] + [InlineData(ErrorType.NotFound, StatusCodes.Status404NotFound)] + [InlineData(ErrorType.Validation, StatusCodes.Status400BadRequest)] + [InlineData(ErrorType.Failure, StatusCodes.Status403Forbidden)] + [InlineData(ErrorType.Unexpected, StatusCodes.Status500InternalServerError)] + public void Problem_WhenCalledWithSingleError_ShouldReturnCorrectStatusCode(ErrorType errorType, int expectedStatusCode) + { + // Arrange + Error error = errorType switch + { + ErrorType.Conflict => Error.Conflict("ErrorCode", "ErrorDescription"), + ErrorType.NotFound => Error.NotFound("ErrorCode", "ErrorDescription"), + ErrorType.Validation => Error.Validation("ErrorCode", "ErrorDescription"), + ErrorType.Failure => Error.Failure("ErrorCode", "ErrorDescription"), + _ => Error.Unexpected("ErrorCode", "ErrorDescription"), + }; + List errors = [error]; + + ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); + mockProblemDetailsFactory.CreateProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ProblemDetails { Status = expectedStatusCode }); + + mockProblemDetailsFactory.CreateValidationProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ValidationProblemDetails { Status = expectedStatusCode }); + + _sut.ProblemDetailsFactory = mockProblemDetailsFactory; + + // Act + IActionResult result = _sut.TestProblem(errors); + + // Assert + if (errorType == ErrorType.Validation) + { + result.Should().BeOfType(); + BadRequestObjectResult badRequestResult = (BadRequestObjectResult)result; + badRequestResult.StatusCode.Should().Be(expectedStatusCode); + badRequestResult.Value.Should().BeOfType(); + ((ValidationProblemDetails)badRequestResult.Value!).Status.Should().Be(expectedStatusCode); + + mockProblemDetailsFactory.Received(1).CreateValidationProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Is(status => status == null), + Arg.Is(title => title == "One or more validation errors occurred."), + Arg.Any(), + Arg.Any(), + Arg.Any()); + } + else + { + result.Should().BeOfType(); + ObjectResult objectResult = (ObjectResult)result; + objectResult.StatusCode.Should().Be(expectedStatusCode); + objectResult.Value.Should().BeOfType(); + ((ProblemDetails)objectResult.Value!).Status.Should().Be(expectedStatusCode); + + mockProblemDetailsFactory.Received(1).CreateProblemDetails( + Arg.Any(), + Arg.Is(status => status == expectedStatusCode), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()); + } + } + + [Fact] + public void Problem_WhenCalledWithMixedErrors_ShouldReturnBadRequestObjectResult() + { + // Arrange + List errors = [ + Error.Validation("ValidationCode", "Validation Error"), + Error.Failure("FailureCode", "Failure Error") + ]; + + ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); + mockProblemDetailsFactory.CreateProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ProblemDetails { Status = StatusCodes.Status400BadRequest }); + + _sut.ProblemDetailsFactory = mockProblemDetailsFactory; + + // Act + IActionResult result = _sut.TestProblem(errors); + + // Assert + result.Should().BeOfType(); + ObjectResult objectResult = (ObjectResult)result; + objectResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest); + objectResult.Value.Should().BeOfType(); + ((ProblemDetails)objectResult.Value!).Status.Should().Be(StatusCodes.Status400BadRequest); + + mockProblemDetailsFactory.Received(1).CreateProblemDetails( + Arg.Any(), + Arg.Is(status => status == StatusCodes.Status400BadRequest), + Arg.Is(title => title == "Validation"), + Arg.Any(), + Arg.Is(detail => detail == "Validation Error"), + Arg.Any()); + } + + [Fact] + public void Problem_WhenCalled_ShouldAddErrorsToHttpContext() + { + // Arrange + List errors = [Error.Failure("ErrorCode", "ErrorDescription")]; + Dictionary mockItems = []; + _mockHttpContext.Items.Returns(mockItems!); + + ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); + mockProblemDetailsFactory.CreateProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ProblemDetails()); + + _sut.ProblemDetailsFactory = mockProblemDetailsFactory; + + // Act + _sut.TestProblem(errors); + + // Assert + mockItems.Should().ContainKey(HttpContextItemKeys.ERRORS); + mockItems[HttpContextItemKeys.ERRORS].Should().BeEquivalentTo(errors); + } + + [Fact] + public void ValidationProblem_WhenCalled_ShouldAddErrorsToModelState() + { + // Arrange + List errors = [ + Error.Validation("Code1", "Description1"), + Error.Validation("Code2", "Description2") + ]; + + _mockProblemDetailsFactory.CreateValidationProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(callInfo => + { + ModelStateDictionary modelState = callInfo.ArgAt(1); + return new ValidationProblemDetails(modelState); + }); + + // Act + IActionResult result = _sut.TestValidationProblem(errors); + + // Assert + result.Should().BeOfType(); + ObjectResult objectResult = (ObjectResult)result; + ValidationProblemDetails validationProblem = objectResult.Value.Should().BeOfType().Subject; + validationProblem.Errors.Should().ContainKeys("Code1", "Code2"); + validationProblem.Errors["Code1"].Should().Contain("Description1"); + validationProblem.Errors["Code2"].Should().Contain("Description2"); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/Fixtures/ApiControllerFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/Fixtures/ApiControllerFixture.cs new file mode 100644 index 00000000..a12a0506 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/Fixtures/ApiControllerFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Presentation.Api.Core.Controllers.Common; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.Common.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ApiControllerFixture : ApiController +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Returns a standardized error response using the format. + /// + /// A list of errors to include in the response. + /// An with the problem details containing the specified errors. + public IActionResult TestProblem(List errors) + { + return Problem(errors); + } + + /// + /// Returns a standardized validation error response using the format. + /// + /// A list of validation errors to include in the response. + /// An with the validation problem details containing the specified errors. + public IActionResult TestValidationProblem(List errors) + { + return ValidationProblem(errors); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/ModelBinders/UrlStringBinderTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/ModelBinders/UrlStringBinderTests.cs new file mode 100644 index 00000000..8d2cc57f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/ModelBinders/UrlStringBinderTests.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Presentation.Api.Common.ModelBinders; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.Extensions.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.ModelBinders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UrlStringBinderTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly UrlStringBinder _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public UrlStringBinderTests() + { + _sut = new UrlStringBinder(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task BindModelAsync_WhenBindingContextIsNull_ShouldThrowArgumentNullException() + { + // Arrange + ModelBindingContext? bindingContext = null; + + // Act & Assert + await Assert.ThrowsAsync(() => _sut.BindModelAsync(bindingContext!)); + } + + [Fact] + public async Task BindModelAsync_WhenValueProviderResultIsNone_ShouldReturnCompletedTask() + { + // Arrange + ModelBindingContext mockBindingContext = Substitute.For(); + mockBindingContext.ValueProvider.GetValue(Arg.Any()).Returns(ValueProviderResult.None); + + // Act + await _sut.BindModelAsync(mockBindingContext); + + // Assert + mockBindingContext.Result.Should().Be(ModelBindingResult.Failed()); + } + + [Fact] + public async Task BindModelAsync_WhenFirstValueIsNull_ShouldSetFailedResult() + { + // Arrange + ModelBindingContext mockBindingContext = Substitute.For(); + ValueProviderResult valueProviderResult = new(new StringValues((string?)null)); + mockBindingContext.ValueProvider.GetValue(Arg.Any()).Returns(valueProviderResult); + + // Act + await _sut.BindModelAsync(mockBindingContext); + + // Assert + mockBindingContext.Result.Should().Be(ModelBindingResult.Failed()); + } + + [Fact] + public async Task BindModelAsync_WhenFirstValueIsNullButValueProviderResultIsNotNone_ShouldSetFailedResult() + { + // Arrange + ModelBindingContext mockBindingContext = Substitute.For(); + ValueProviderResult valueProviderResult = new(new StringValues([null])); + mockBindingContext.ValueProvider.GetValue(Arg.Any()).Returns(valueProviderResult); + + // Act + await _sut.BindModelAsync(mockBindingContext); + + // Assert + mockBindingContext.Result.Should().Be(ModelBindingResult.Failed()); + } + + [Fact] + public async Task BindModelAsync_WhenValueIsProvided_ShouldDecodeAndSetSuccessResult() + { + // Arrange + const string ENCODED_VALUE = "Hello%20World%21"; + const string DECODED_VALUE = "Hello World!"; + ModelBindingContext mockBindingContext = Substitute.For(); + mockBindingContext.ValueProvider.GetValue(Arg.Any()).Returns(new ValueProviderResult(ENCODED_VALUE)); + + // Act + await _sut.BindModelAsync(mockBindingContext); + + // Assert + mockBindingContext.Result.Should().Be(ModelBindingResult.Success(DECODED_VALUE)); + } + + [Fact] + public async Task BindModelAsync_ShouldUseProvidedModelName() + { + // Arrange + const string MODEL_NAME = "testModel"; + ModelBindingContext mockBindingContext = Substitute.For(); + mockBindingContext.ModelName.Returns(MODEL_NAME); + + // Act + await _sut.BindModelAsync(mockBindingContext); + + // Assert + mockBindingContext.ValueProvider.Received(1).GetValue(MODEL_NAME); + } + #endregion +}