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/Users/Queries/GetUserById.cs
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
using Application.Common.Interfaces;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Application.Users.Queries;

Expand All@@ -8,4 +11,29 @@ public record Query : IRequest<UserDto>
{
public Guid UserId { get; init; }
}

public class QueryHandler : IRequestHandler<Query, UserDto>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;

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

public async Task<UserDto> 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<UserDto>(user);
}
}
}
Original file line numberDiff line numberDiff line change
@@ -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<KeyNotFoundException>()
.WithMessage("User does not exist.");
}
}