using Heimdall.Application.Common; using Heimdall.Application.Persons.Commands.UpdatePerson; using Heimdall.Application.Tests.Common; using Heimdall.Domain.Entities; using Microsoft.EntityFrameworkCore; using NSubstitute; namespace Heimdall.Application.Tests.Handlers.Persons; public class UpdatePersonHandlerTests { [Fact] public async Task Update_person_should_return_success() { var person = new Person("Old Name", "family"); var context = Substitute.For(); context.Persons.Returns(MockDbSetHelper.CreateFor([person])); context.AuditLogs.Returns(Substitute.For>()); var handler = new UpdatePersonCommandHandler(context); var result = await handler.Handle( new UpdatePersonCommand(person.Id, "New Name", "Some notes", "employee", true), CancellationToken.None); result.IsSuccess.ShouldBeTrue(); result.Data.ShouldNotBeNull(); result.Data.DisplayName.ShouldBe("New Name"); result.Data.IsWatchlisted.ShouldBeTrue(); await context.Received(1).SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); } [Fact] public async Task Update_nonexistent_person_should_return_not_found() { var context = Substitute.For(); context.Persons.Returns(MockDbSetHelper.CreateFor()); context.AuditLogs.Returns(Substitute.For>()); var handler = new UpdatePersonCommandHandler(context); var result = await handler.Handle( new UpdatePersonCommand(Guid.NewGuid(), "Name", null, null, false), CancellationToken.None); result.IsSuccess.ShouldBeFalse(); result.StatusCode.ShouldBe(404); } [Fact] public async Task Update_person_should_record_audit_log() { var person = new Person("Old Name", "family"); var actorId = Guid.NewGuid(); AuditLog? entry = null; var context = Substitute.For(); context.Persons.Returns(MockDbSetHelper.CreateFor([person])); var auditLogs = Substitute.For>(); auditLogs.When(set => set.Add(Arg.Any())).Do(call => entry = call.Arg()); context.AuditLogs.Returns(auditLogs); var handler = new UpdatePersonCommandHandler(context); var result = await handler.Handle( new UpdatePersonCommand(person.Id, "New Name", "Some notes", "employee", true, actorId), CancellationToken.None); result.IsSuccess.ShouldBeTrue(); entry.ShouldNotBeNull(); entry.UserId.ShouldBe(actorId); entry.OldValue!.ShouldContain("Old Name"); entry.NewValue!.ShouldContain("New Name"); } }