mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 02:11:10 +00:00
Refactors the get book slice
This commit is contained in:
1 parent
1d35cd01db
commit
8aaf9fe64e
17 files changed
+395
-347
No files matched your search
-46
@@ -1,46 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetBookRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBookRequestMappingTests
|
||||
{
|
||||
private readonly GetBookRequestFixture _requestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingRequestWithValidId_ShouldMapIdCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
GetBookRequest request = _requestFixture.Create(id: bookId.ToString());
|
||||
|
||||
// Act
|
||||
GetBookQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(bookId, result.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingRequestWithInvalidId_ShouldMapEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _requestFixture.Create(id: "not-a-guid");
|
||||
|
||||
// Act
|
||||
GetBookQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(Guid.Empty, result.Id);
|
||||
}
|
||||
}
|
||||
+46
-30
@@ -1,15 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
@@ -18,9 +15,7 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
@@ -36,14 +31,12 @@ public class GetBookQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IMediaContributorRepository _mockMediaContributorRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetBookQuery> _mockValidator;
|
||||
private readonly GetBookQueryHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly GetBookQueryFixture _getBookQueryFixture = new();
|
||||
|
||||
@@ -53,10 +46,9 @@ public class GetBookQueryHandlerTests
|
||||
public GetBookQueryHandlerTests()
|
||||
{
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<GetBookQuery>>();
|
||||
@@ -76,8 +68,10 @@ public class GetBookQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetBookQuery query = _getBookQueryFixture.Create();
|
||||
BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id);
|
||||
_mockBookRepository.GetByIdAsync(query.Id, Arg.Any<CancellationToken>())
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(bookEntity));
|
||||
|
||||
// Act
|
||||
@@ -85,27 +79,27 @@ public class GetBookQueryHandlerTests
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(query.Id, result.Value.Id);
|
||||
Assert.Equal(bookId, result.Value.Id);
|
||||
Assert.Equal(bookEntity.Title, result.Value.Metadata!.Title);
|
||||
Assert.Null(result.Value.Contributors);
|
||||
await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
|
||||
Assert.NotNull(result.Value.Contributors);
|
||||
Assert.Empty(result.Value.Contributors!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookHasContributors_ShouldReturnResponseWithResolvedContributorNames()
|
||||
public async Task HandleAsync_WhenBookHasContributors_ShouldReturnResponseWithContributorReferences()
|
||||
{
|
||||
// Arrange
|
||||
GetBookQuery query = _getBookQueryFixture.Create();
|
||||
BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id);
|
||||
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
bookEntity.BookContributors =
|
||||
[
|
||||
_bookContributorEntityFixture.Create(bookId: query.Id, mediaContributorId: contributor.Id, roleName: "author", roleCategory: MediaContributorRoleCategory.Author)
|
||||
_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author)
|
||||
];
|
||||
_mockBookRepository.GetByIdAsync(query.Id, Arg.Any<CancellationToken>())
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(bookEntity));
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([contributor]));
|
||||
|
||||
// Act
|
||||
Result<BookResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -114,8 +108,8 @@ public class GetBookQueryHandlerTests
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value.Contributors);
|
||||
Assert.Single(result.Value.Contributors!);
|
||||
Assert.Equal(contributor.DisplayName, result.Value.Contributors![0].Name!.DisplayName);
|
||||
Assert.Equal("author", result.Value.Contributors![0].Role!.Name);
|
||||
Assert.Equal(contributorId, result.Value.Contributors![0].ContributorId);
|
||||
Assert.Equal(MediaContributorRole.Author, result.Value.Contributors![0].Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -123,7 +117,8 @@ public class GetBookQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetBookQuery query = _getBookQueryFixture.Create();
|
||||
_mockBookRepository.GetByIdAsync(query.Id, Arg.Any<CancellationToken>())
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(null));
|
||||
|
||||
// Act
|
||||
@@ -135,12 +130,32 @@ public class GetBookQueryHandlerTests
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetBookQuery query = _getBookQueryFixture.Create();
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid());
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(bookEntity));
|
||||
|
||||
// Act
|
||||
Result<BookResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetBookQuery query = _getBookQueryFixture.Create();
|
||||
_mockBookRepository.GetByIdAsync(query.Id, Arg.Any<CancellationToken>())
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
@@ -156,8 +171,10 @@ public class GetBookQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetBookQuery query = _getBookQueryFixture.Create();
|
||||
BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id);
|
||||
_mockBookRepository.GetByIdAsync(query.Id, Arg.Any<CancellationToken>())
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(bookEntity));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
@@ -170,7 +187,6 @@ public class GetBookQueryHandlerTests
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == bookEntity.LibraryId), Arg.Any<CancellationToken>());
|
||||
await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -186,7 +202,7 @@ public class GetBookQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -203,7 +219,7 @@ public class GetBookQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+26
-5
@@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
@@ -21,7 +20,7 @@ public class GetBookQueryValidatorTests
|
||||
private readonly GetBookQueryValidator _validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenIdIsValid_ShouldNotHaveValidationError()
|
||||
public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBookQuery query = _queryBookFixture.Create();
|
||||
@@ -30,14 +29,36 @@ public class GetBookQueryValidatorTests
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenIdIsEmpty_ShouldHaveValidationError()
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData("not-a-library-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
|
||||
{
|
||||
// Arrange
|
||||
GetBookQuery query = _queryBookFixture.Create(id: Guid.Empty);
|
||||
GetBookQuery query = _queryBookFixture.Create() with { LibraryId = libraryId };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData("not-a-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
|
||||
{
|
||||
// Arrange
|
||||
GetBookQuery query = _queryBookFixture.Create() with { BookId = bookId };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetBookRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBookRequestTests
|
||||
{
|
||||
private readonly GetBookRequestFixture _getBookRequestFixture = new();
|
||||
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalled_ShouldReturnValidGetBookRequest()
|
||||
{
|
||||
// Act
|
||||
GetBookRequest sut = _getBookRequestFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut);
|
||||
Assert.False(string.IsNullOrWhiteSpace(sut.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenPassingNullId_ShouldReturnNullId()
|
||||
{
|
||||
// Act
|
||||
GetBookRequest sut = new(Id: null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_WhenSerializingGetBookRequest_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest expected = _getBookRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
GetBookRequest? actual = JsonSerializer.Deserialize<GetBookRequest>(json, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(actual);
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
}
|
||||
+68
-18
@@ -1,11 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -27,7 +25,6 @@ public class GetBookEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetBookQuery, Result<BookResponse>> _mockHandler;
|
||||
private readonly GetBookEndpoint _sut;
|
||||
private readonly GetBookRequestFixture _getBookRequestFixture = new();
|
||||
private readonly BookResponseFixture _bookResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -36,21 +33,24 @@ public class GetBookEndpointTests
|
||||
public GetBookEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetBookQuery, Result<BookResponse>>>();
|
||||
_sut = Factory.Create<GetBookEndpoint>(_mockHandler);
|
||||
_sut = FastEndpoints.Factory.Create<GetBookEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookResponse()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookResponse expectedResponse = _bookResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<BookResponse> okResult = Assert.IsType<Ok<BookResponse>>(result);
|
||||
@@ -61,14 +61,17 @@ public class GetBookEndpointTests
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
@@ -85,14 +88,17 @@ public class GetBookEndpointTests
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Error.Validation(description: "BookIdCannotBeEmpty");
|
||||
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
@@ -101,27 +107,68 @@ public class GetBookEndpointTests
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetBookQueryToHandler()
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetBookQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
GetBookRequest request = _getBookRequestFixture.Create(id: bookId.ToString());
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetBookQuery>(query => query.Id == bookId),
|
||||
Arg.Is<GetBookQuery>(query => query.LibraryId == libraryId.ToString() && query.BookId == bookId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetBookQuery>(query => query.LibraryId == "not-a-library-guid" && query.BookId == "not-a-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("bookId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetBookQuery>(query => query.LibraryId == null && query.BookId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
@@ -129,7 +176,8 @@ public class GetBookEndpointTests
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
@@ -142,9 +190,11 @@ public class GetBookEndpointTests
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_bookResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
Reference in new issue
Block a user