diff --git a/src/Application/Departments/Queries/GetDepartmentById.cs b/src/Application/Departments/Queries/GetDepartmentById.cs index e4120c64..83f3f725 100644 --- a/src/Application/Departments/Queries/GetDepartmentById.cs +++ b/src/Application/Departments/Queries/GetDepartmentById.cs @@ -1,5 +1,9 @@ +using Application.Common.Interfaces; using Application.Common.Models.Dtos; +using Application.Common.Models.Dtos.Physical; +using AutoMapper; using MediatR; +using Microsoft.EntityFrameworkCore; namespace Application.Departments.Queries; @@ -9,4 +13,28 @@ public record Query : IRequest { public Guid DepartmentId { 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 department = await _context.Departments.FirstOrDefaultAsync(x => x.Id.Equals(request.DepartmentId), cancellationToken); + + if (department is null) + { + throw new KeyNotFoundException("Department does not exist."); + } + + return _mapper.Map(department); + } + } + } \ No newline at end of file diff --git a/tests/Application.Tests.Integration/Departments/Queries/GetDepartmentByIdTests.cs b/tests/Application.Tests.Integration/Departments/Queries/GetDepartmentByIdTests.cs new file mode 100644 index 00000000..af7d9df8 --- /dev/null +++ b/tests/Application.Tests.Integration/Departments/Queries/GetDepartmentByIdTests.cs @@ -0,0 +1,52 @@ +using Application.Departments.Queries; +using FluentAssertions; +using Xunit; + +namespace Application.Tests.Integration.Departments.Queries; + +public class GetDepartmentByIdTests : BaseClassFixture +{ + public GetDepartmentByIdTests(CustomApiFactory apiFactory) : base(apiFactory) + { + } + + [Fact] + public async Task ShouldReturnDepartment_WhenThatDepartmentExists() + { + // Arrange + var department = CreateDepartment(); + + await AddAsync(department); + + var query = new GetDepartmentById.Query() + { + DepartmentId = department.Id, + }; + + // Act + var result = await SendAsync(query); + + // Assert + result.Name.Should().Be(department.Name); + + // Cleanup + Remove(department); + } + + [Fact] + public async Task ShouldThrowNotFoundException_WhenThatDepartmentDoesNotExist() + { + // Arrange + var query = new GetDepartmentById.Query() + { + DepartmentId = Guid.NewGuid(), + }; + + // Act + var action = async () => await SendAsync(query); + + // Assert + await action.Should().ThrowAsync() + .WithMessage("Department does not exist."); + } +} \ No newline at end of file