Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/Application/Departments/Queries/GetDepartmentById.cs
Original file line numberDiff line numberDiff line change
@@ -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;

Expand All@@ -9,4 +13,28 @@ public record Query : IRequest<DepartmentDto>
{
public Guid DepartmentId { get; init; }
}
public class QueryHandler : IRequestHandler<Query, DepartmentDto>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;

public QueryHandler(IApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}

public async Task<DepartmentDto> 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<DepartmentDto>(department);
}
}

}
Original file line numberDiff line numberDiff line change
@@ -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<KeyNotFoundException>()
.WithMessage("Department does not exist.");
}
}