Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
using System.Linq.Expressions;
using AutoMapper;
using Hng.Application.Features.Comments.Commands;
using Hng.Application.Features.Comments.Dtos;
using Hng.Application.Features.Comments.Handlers;
using Hng.Domain.Entities;
using Hng.Infrastructure.Repository.Interface;
using Hng.Infrastructure.Services.Interfaces;
using Moq;
using Xunit;

public class UpdateCommentCommandShould
{
private readonly IMapper _mapper;
private readonly Mock<IRepository<Comment>> _commentRepositoryMock;
private readonly Mock<IAuthenticationService> _authenticationServiceMock;
private readonly UpdateCommentCommandHandler _handler;

public UpdateCommentCommandShould()
{
// Setup AutoMapper
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<UpdateCommentDto, Comment>().ReverseMap();
cfg.CreateMap<Comment, CommentDto>().ReverseMap();
});
_mapper = configuration.CreateMapper();

_commentRepositoryMock = new Mock<IRepository<Comment>>();
_authenticationServiceMock = new Mock<IAuthenticationService>();
_handler = new UpdateCommentCommandHandler(
_mapper,
_commentRepositoryMock.Object,
_authenticationServiceMock.Object
);
}

[Fact]
public async Task Handle_ShouldUpdateCommentSuccessfully()
{
// Arrange
var blogId = Guid.NewGuid();
var commentId = Guid.NewGuid();
var userId = Guid.NewGuid();
var updateCommentDto = new UpdateCommentDto { Content = "Updated content" };
var comment = new Comment
{
Id = commentId,
BlogId = blogId,
AuthorId = userId,
Content = "Original content",
UpdatedAt = DateTime.UtcNow
};

_commentRepositoryMock
.Setup(r => r.GetBySpec(It.IsAny<Expression<Func<Comment, bool>>>()))
.ReturnsAsync(comment);

_authenticationServiceMock
.Setup(s => s.GetCurrentUserAsync())
.ReturnsAsync(userId);

_commentRepositoryMock
.Setup(r => r.UpdateAsync(It.IsAny<Comment>()))
.Returns(Task.CompletedTask);

_commentRepositoryMock
.Setup(r => r.SaveChanges())
.Returns(Task.CompletedTask);

// Act
var result = await _handler.Handle(
new UpdateCommentCommand(blogId, commentId, updateCommentDto, userId),
CancellationToken.None
);

// Assert
Assert.NotNull(result);
Assert.Equal(200, result.StatusCode);
Assert.Equal("Comment updated successfully", result.Message);
Assert.Equal("Updated content", result.Data.Content);
_commentRepositoryMock.Verify(r => r.UpdateAsync(It.IsAny<Comment>()), Times.Once);
_commentRepositoryMock.Verify(r => r.SaveChanges(), Times.Once);
}

[Fact]
public async Task Handle_ShouldReturnNotFound_WhenCommentNotFound()
{
// Arrange
var blogId = Guid.NewGuid();
var commentId = Guid.NewGuid();
var userId = Guid.NewGuid();
var updateCommentDto = new UpdateCommentDto { Content = "Updated content" };

_commentRepositoryMock
.Setup(r => r.GetBySpec(It.IsAny<Expression<Func<Comment, bool>>>()))
.ReturnsAsync((Comment)null);

_authenticationServiceMock
.Setup(s => s.GetCurrentUserAsync())
.ReturnsAsync(userId);

// Act
var result = await _handler.Handle(
new UpdateCommentCommand(blogId, commentId, updateCommentDto, userId),
CancellationToken.None
);

// Assert
Assert.NotNull(result);
Assert.Equal(404, result.StatusCode);
Assert.Equal("Comment not found.", result.Message);
Assert.Null(result.Data);
}

[Fact]
public async Task Handle_ShouldReturnUnauthorized_WhenUserIsNotAuthorized()
{
// Arrange
var blogId = Guid.NewGuid();
var commentId = Guid.NewGuid();
var userId = Guid.NewGuid();
var anotherUserId = Guid.NewGuid();
var updateCommentDto = new UpdateCommentDto { Content = "Updated content" };
var comment = new Comment
{
Id = commentId,
BlogId = blogId,
AuthorId = userId,
Content = "Original content",
UpdatedAt = DateTime.UtcNow
};

_commentRepositoryMock
.Setup(r => r.GetBySpec(It.IsAny<Expression<Func<Comment, bool>>>()))
.ReturnsAsync(comment);

_authenticationServiceMock
.Setup(s => s.GetCurrentUserAsync())
.ReturnsAsync(anotherUserId);

// Act
var result = await _handler.Handle(
new UpdateCommentCommand(blogId, commentId, updateCommentDto, anotherUserId),
CancellationToken.None
);

// Assert
Assert.NotNull(result);
Assert.Equal(403, result.StatusCode);
Assert.Equal("You are not authorized to update this comment.", result.Message);
Assert.Null(result.Data);
}

[Fact]
public async Task Handle_ShouldReturnBadRequest_WhenContentIsEmpty()
{
// Arrange
var blogId = Guid.NewGuid();
var commentId = Guid.NewGuid();
var userId = Guid.NewGuid();
var updateCommentDto = new UpdateCommentDto { Content = string.Empty };
var comment = new Comment
{
Id = commentId,
BlogId = blogId,
AuthorId = userId,
Content = "Original content",
UpdatedAt = DateTime.UtcNow
};

_commentRepositoryMock
.Setup(r => r.GetBySpec(It.IsAny<Expression<Func<Comment, bool>>>()))
.ReturnsAsync(comment);

_authenticationServiceMock
.Setup(s => s.GetCurrentUserAsync())
.ReturnsAsync(userId);

// Act
var result = await _handler.Handle(
new UpdateCommentCommand(blogId, commentId, updateCommentDto, userId),
CancellationToken.None
);

// Assert
Assert.NotNull(result);
Assert.Equal(400, result.StatusCode);
Assert.Equal("Comment cannot be empty.", result.Message);
Assert.Null(result.Data);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Hng.Application.Features.Comments.Dtos;
using Hng.Application.Shared.Dtos;
using MediatR;

namespace Hng.Application.Features.Comments.Commands
{
public class UpdateCommentCommand(Guid blogId, Guid commentId, UpdateCommentDto body, Guid userId) : IRequest<SuccessResponseDto<CommentDto>>
{
public Guid BlogId { get; } = blogId;
public Guid commentId { get; } = commentId;
public UpdateCommentDto CommentBody { get; } = body;
public Guid userId { get; } = userId;
}
}
2 changes: 2 additions & 0 deletions src/Hng.Application/Features/Comments/Dtos/CommentDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ public class CommentDto
public string Content { get; set; }
[JsonPropertyName("created_at")]
public DateTime CreatedAt { get; set; }
[JsonPropertyName("updated_at")]
public DateTime? UpdatedAt { get; set; }
}
10 changes: 10 additions & 0 deletions src/Hng.Application/Features/Comments/Dtos/UpdateCommentDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

namespace Hng.Application.Features.Comments.Dtos;

public class UpdateCommentDto
{
[JsonPropertyName("content")]
public string Content { get; set; } = string.Empty;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using AutoMapper;
using Hng.Application.Features.Comments.Commands;
using Hng.Application.Features.Comments.Dtos;
using Hng.Application.Shared.Dtos;
using Hng.Domain.Entities;
using Hng.Infrastructure.Repository.Interface;
using Hng.Infrastructure.Services.Interfaces;
using MediatR;

namespace Hng.Application.Features.Comments.Handlers;

public class UpdateCommentCommandHandler(
IMapper mapper,
IRepository<Comment> commentRepository,
IAuthenticationService authenticationService)
: IRequestHandler<UpdateCommentCommand, SuccessResponseDto<CommentDto>>
{
private readonly IMapper _mapper = mapper;
private readonly IRepository<Comment> _commentRepository = commentRepository;
private readonly IAuthenticationService _authenticationService = authenticationService;

public async Task<SuccessResponseDto<CommentDto>> Handle(UpdateCommentCommand request, CancellationToken cancellationToken)
{
var comment = await _commentRepository.GetBySpec(c => c.Id == request.commentId && c.BlogId == request.BlogId);
if (comment == null)
{
return new SuccessResponseDto<CommentDto>
{
Data = null,
Message = "Comment not found.",
StatusCode = 404
};
}

var userId = await _authenticationService.GetCurrentUserAsync();
if (comment.AuthorId != userId)
{
return new SuccessResponseDto<CommentDto>
{
Data = null,
Message = "You are not authorized to update this comment.",
StatusCode = 403
};
}

if (string.IsNullOrWhiteSpace(request.CommentBody.Content))
{
return new SuccessResponseDto<CommentDto>
{
Data = null,
Message = "Comment cannot be empty.",
StatusCode = 400
};
}

// Update only the content field
comment.Content = request.CommentBody.Content;
comment.UpdatedAt = DateTime.UtcNow;

await _commentRepository.UpdateAsync(comment);
await _commentRepository.SaveChanges();

return new SuccessResponseDto<CommentDto>
{
Data = _mapper.Map<CommentDto>(comment),
Message = "Comment updated successfully",
StatusCode = 200
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public class CommentMapperProfile : Profile
public CommentMapperProfile()
{
CreateMap<CreateCommentDto, Comment>();
CreateMap<UpdateCommentDto, Comment>();
CreateMap<Comment, CommentDto>()
.ReverseMap();
}
Expand Down
3 changes: 2 additions & 1 deletion src/Hng.Domain/Entities/Comment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ public class Comment : EntityBase
public Guid AuthorId { get; set; }
public User Author { get; set; }

public DateTime CreatedAt { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime? UpdatedAt { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,9 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");

b.Property<DateTime?>("UpdatedAt")
.HasColumnType("timestamp with time zone");

b.HasKey("Id");

b.HasIndex("AuthorId");
Expand Down
22 changes: 21 additions & 1 deletion src/Hng.Web/Controllers/CommentController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Hng.Application.Features.Comments.Dtos;
using Hng.Application.Features.Comments.Queries;
using Hng.Application.Shared.Dtos;
using Hng.Infrastructure.Services.Interfaces;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -11,9 +12,11 @@ namespace Hng.Web.Controllers;
[Authorize]
[ApiController]
[Route("api/v1/posts/{blogId:guid}/comments")]
public class CommentController(IMediator mediator) : ControllerBase
public class CommentController(IMediator mediator, IAuthenticationService authenticationService) : ControllerBase
{
private readonly IMediator _mediator = mediator;
private readonly IAuthenticationService _authenticationService = authenticationService;


[HttpPost]
[ProducesResponseType(typeof(CommentDto), StatusCodes.Status201Created)]
Expand All @@ -37,4 +40,21 @@ public async Task<ActionResult<IEnumerable<CommentDto>>> GetCommentsByBlogId([Fr
};
return Ok(response);
}

[HttpPut("{commentId:guid}")]
[ProducesResponseType(typeof(CommentDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<CommentDto>> UpdateComment(
[FromRoute] Guid blogId,
[FromRoute] Guid commentId,
[FromBody] UpdateCommentDto body)
{
var userId = await _authenticationService.GetCurrentUserAsync();
var command = new UpdateCommentCommand(blogId, commentId, body, userId);
var updatedComment = await _mediator.Send(command);

return Ok(updatedComment);
}
}
Loading