using MemeVault.Application.Commands.SetCollectionInbox; using MemeVault.Application.Common; using MemeVault.Domain.Aggregates.BotUser; using MemeVault.Domain.Aggregates.Collection; using MemeVault.Domain.Exceptions; using MemeVault.Domain.Repositories; using NSubstitute; using Xunit; namespace MemeVault.Tests.Unit.Handlers; public sealed class SetCollectionInboxCommandHandlerTests { private readonly ICollectionRepository _collections = Substitute.For(); private readonly IBotUserRepository _users = Substitute.For(); private readonly IUnitOfWork _uow = Substitute.For(); private readonly SetCollectionInboxCommandHandler _handler; private const long UserId = 42L; public SetCollectionInboxCommandHandlerTests() { _handler = new SetCollectionInboxCommandHandler(_collections, _users, _uow); } [Fact] public async Task Handle_CollectionNotFound_ReturnsFalse() { _collections.GetByIdAsync(Arg.Any(), Arg.Any()) .Returns((Collection?)null); var result = await _handler.Handle( new SetCollectionInboxCommand(Guid.NewGuid(), UserId), default); Assert.False(result); await _uow.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] public async Task Handle_NotOwner_ReturnsFalse() { var col = Collection.Create(999L, "Alien Collection"); // owned by 999, not UserId _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); var result = await _handler.Handle( new SetCollectionInboxCommand(col.Id, UserId), default); Assert.False(result); await _uow.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] public async Task Handle_UserNotFound_ReturnsFalse() { var col = Collection.Create(UserId, "My Collection"); _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); _users.GetByTelegramIdAsync(UserId, Arg.Any()).Returns((BotUser?)null); var result = await _handler.Handle( new SetCollectionInboxCommand(col.Id, UserId), default); Assert.False(result); } [Fact] public async Task Handle_AlreadyInbox_ThrowsInboxProtectionException() { var col = Collection.Create(UserId, "Inbox"); _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); var user = BotUser.Create(UserId, "testuser", null); user.SetInboxCollection(col.Id); // уже является Inbox _users.GetByTelegramIdAsync(UserId, Arg.Any()).Returns(user); await Assert.ThrowsAsync(() => _handler.Handle(new SetCollectionInboxCommand(col.Id, UserId), default)); } [Fact] public async Task Handle_ValidRequest_SetsInboxAndSaves() { var oldInbox = Guid.NewGuid(); var newCol = Collection.Create(UserId, "New Inbox"); _collections.GetByIdAsync(newCol.Id, Arg.Any()).Returns(newCol); var user = BotUser.Create(UserId, "testuser", null); user.SetInboxCollection(oldInbox); _users.GetByTelegramIdAsync(UserId, Arg.Any()).Returns(user); var result = await _handler.Handle( new SetCollectionInboxCommand(newCol.Id, UserId), default); Assert.True(result); Assert.Equal(newCol.Id, user.InboxCollectionId); await _users.Received(1).UpdateAsync(user, Arg.Any()); await _uow.Received(1).SaveChangesAsync(Arg.Any()); } }