diff --git a/src/Application/Users/Queries/GetUserById.cs b/src/Application/Users/Queries/GetUserById.cs index e34b58d2..c4cd1278 100644 --- a/src/Application/Users/Queries/GetUserById.cs +++ b/src/Application/Users/Queries/GetUserById.cs @@ -1,4 +1,7 @@ +using Application.Common.Interfaces; +using AutoMapper; using MediatR; +using Microsoft.EntityFrameworkCore; namespace Application.Users.Queries; @@ -8,4 +11,29 @@ public record Query : IRequest { public Guid UserId { get; init; } } + + public class QueryHandler : IRequestHandler + { + private readonly IApplicationDbContext _context; + private readonly IMapper _mapper; + + public QueryHandler(IApplicationDbContext context, IMapper mapper) + { + _context = context; + _mapper = mapper; + } + + public async Task Handle(Query request, CancellationToken cancellationToken) + { + var user = await _context.Users + .FirstOrDefaultAsync(x => x.Id.Equals(request.UserId), cancellationToken: cancellationToken); + + if (user is null) + { + throw new KeyNotFoundException("User does not exist."); + } + + return _mapper.Map(user); + } + } } \ No newline at end of file diff --git a/tests/Application.Tests.Integration/Users/Queries/GetUserByIdTests.cs b/tests/Application.Tests.Integration/Users/Queries/GetUserByIdTests.cs new file mode 100644 index 00000000..f6a758be --- /dev/null +++ b/tests/Application.Tests.Integration/Users/Queries/GetUserByIdTests.cs @@ -0,0 +1,59 @@ +using Application.Identity; +using Application.Users.Queries; +using FluentAssertions; +using Xunit; + +namespace Application.Tests.Integration.Users.Queries; + +public class GetUserByIdTests : BaseClassFixture +{ + public GetUserByIdTests(CustomApiFactory apiFactory) : base(apiFactory) + { + } + + [Fact] + public async Task ShouldReturnUser_WhenThatUserExists() + { + // Arrange + var user = CreateUser(IdentityData.Roles.Employee, "randomPassword"); + await AddAsync(user); + + var query = new GetUserById.Query() + { + UserId = user.Id, + }; + + // Act + var result = await SendAsync(query); + + // Assert + result.Username.Should().Be(user.Username); + result.Email.Should().Be(user.Email); + result.FirstName.Should().Be(user.FirstName); + result.LastName.Should().Be(user.LastName); + result.Role.Should().Be(user.Role); + result.Position.Should().Be(user.Position); + result.IsActivated.Should().Be(user.IsActivated); + result.IsActive.Should().Be(user.IsActive); + + // Cleanup + Remove(user); + } + + [Fact] + public async Task ShouldThrowKeyNotFoundException_WhenThatUserDoesNotExist() + { + // Arrange + var query = new GetUserById.Query() + { + UserId = Guid.NewGuid(), + }; + + // Act + var action = async () => await SendAsync(query); + + // Assert + await action.Should().ThrowAsync() + .WithMessage("User does not exist."); + } +} \ No newline at end of file