Skip to content

Instantly share code, notes, and snippets.

@Msirkovsky
Created March 16, 2024 17:10
Show Gist options
  • Save Msirkovsky/ab5dd02bb35121b6deaa6c025a165383 to your computer and use it in GitHub Desktop.
Save Msirkovsky/ab5dd02bb35121b6deaa6c025a165383 to your computer and use it in GitHub Desktop.
JetBrains AI - DeleteUserCommandHandlerTests
namespace AssistantsAI.Commands;
public class DeleteUserCommandHandlerTests
{
[Fact]
public async Task Should_Delete_User_If_Exists_And_NotLocked()
{
// Arrange
var mockContext = new Mock<MyDbContext>();
var mockDbSet = new Mock<DbSet<User>>();
var userId = 1;
var user = new User { User_Id = userId, Locked = false };
mockDbSet.Setup(x => x.FindAsync(userId)).Returns(new ValueTask<User>(user));
mockDbSet.Setup(x => x.Remove(It.IsAny<User>())).Callback<User>((s) => { });
mockContext.Setup(x => x.Users).Returns(mockDbSet.Object);
var handler = new DeleteUserCommandHandler(mockContext.Object);
var request = new DeleteUserCommandInput(userId);
// Act
await handler.Handle(request, new CancellationToken());
// Assert
mockDbSet.Verify(x => x.Remove(It.IsAny<User>()), Times.Once);
mockContext.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Should_Not_Delete_User_If_Locked()
{
// Arrange
var mockContext = new Mock<MyDbContext>();
var mockDbSet = new Mock<DbSet<User>>();
var userId = 1;
var user = new User { User_Id = userId, Locked = true };
mockDbSet.Setup(x => x.FindAsync(userId)).Returns(new ValueTask<User>(user));
mockDbSet.Setup(x => x.Remove(It.IsAny<User>())).Callback<User>((s) => { });
mockContext.Setup(x => x.Users).Returns(mockDbSet.Object);
var handler = new DeleteUserCommandHandler(mockContext.Object);
var request = new DeleteUserCommandInput(userId);
// Act
await handler.Handle(request, new CancellationToken());
// Assert
mockDbSet.Verify(x => x.Remove(It.IsAny<User>()), Times.Never);
mockContext.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Never);
}
[Fact]
public async Task Should_Not_Delete_User_If_Not_Exists()
{
// Arrange
var mockContext = new Mock<MyDbContext>();
var mockDbSet = new Mock<DbSet<User>>();
var userId = 1;
mockDbSet.Setup(x => x.FindAsync(userId)).Returns(new ValueTask<User>((User)null));
mockDbSet.Setup(x => x.Remove(It.IsAny<User>())).Callback<User>((s) => { });
mockContext.Setup(x => x.Users).Returns(mockDbSet.Object);
var handler = new DeleteUserCommandHandler(mockContext.Object);
var request = new DeleteUserCommandInput(userId);
// Act
await handler.Handle(request, new CancellationToken());
// Assert
mockDbSet.Verify(x => x.Remove(It.IsAny<User>()), Times.Never);
mockContext.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Never);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment