diff --git a/src/Application/Rooms/Queries/GetRoomById.cs b/src/Application/Rooms/Queries/GetRoomById.cs index 6a3657bd..6e834b68 100644 --- a/src/Application/Rooms/Queries/GetRoomById.cs +++ b/src/Application/Rooms/Queries/GetRoomById.cs @@ -1,5 +1,9 @@ +using Application.Common.Interfaces; using Application.Common.Models.Dtos.Physical; +using AutoMapper; +using FluentValidation; using MediatR; +using Microsoft.EntityFrameworkCore; namespace Application.Rooms.Queries; @@ -9,4 +13,29 @@ public record Query : IRequest { public Guid RoomId { 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 room = await _context.Rooms + .FirstOrDefaultAsync(x => x.Id.Equals(request.RoomId), cancellationToken: cancellationToken); + + if (room is null) + { + throw new KeyNotFoundException("Room does not exist."); + } + + return _mapper.Map(room); + } + } } \ No newline at end of file diff --git a/tests/Application.Tests.Integration/Rooms/Queries/GetRoomByIdTests.cs b/tests/Application.Tests.Integration/Rooms/Queries/GetRoomByIdTests.cs new file mode 100644 index 00000000..1f3ee018 --- /dev/null +++ b/tests/Application.Tests.Integration/Rooms/Queries/GetRoomByIdTests.cs @@ -0,0 +1,55 @@ +using Application.Rooms.Queries; +using Domain.Entities; +using FluentAssertions; +using Xunit; + +namespace Application.Tests.Integration.Rooms.Queries; + +public class GetRoomByIdTests : BaseClassFixture +{ + public GetRoomByIdTests(CustomApiFactory apiFactory) : base(apiFactory) + { + } + + [Fact] + public async Task ShouldReturnRoom_WhenThatRoomExists() + { + // Arrange + var department = CreateDepartment(); + var room = CreateRoom(department); + await AddAsync(room); + + var query = new GetRoomById.Query() + { + RoomId = room.Id, + }; + + // Act + var result = await SendAsync(query); + + // Assert + result.Id.Should().Be(room.Id); + result.Name.Should().Be(room.Name); + + // Cleanup + Remove(room); + Remove(await FindAsync(department.Id)); + } + + [Fact] + public async Task ShouldThrowKeyNotFoundException_WhenThatRoomDoesNotExist() + { + // Arrange + var query = new GetRoomById.Query() + { + RoomId = Guid.NewGuid(), + }; + + // Act + var action = async () => await SendAsync(query); + + // Assert + await action.Should().ThrowAsync() + .WithMessage("Room does not exist."); + } +} \ No newline at end of file