| package com.pt5.pthouduan.service; |
| |
| import com.pt5.pthouduan.entity.Comment; |
| import org.junit.jupiter.api.BeforeEach; |
| import org.junit.jupiter.api.Test; |
| import org.mockito.Mock; |
| import org.mockito.MockitoAnnotations; |
| |
| import java.time.LocalDateTime; |
| import java.util.Collections; |
| import java.util.List; |
| |
| import static org.junit.jupiter.api.Assertions.*; |
| import static org.mockito.Mockito.*; |
| |
| class CommentServiceTest { |
| |
| @Mock |
| private CommentService commentService; |
| |
| @BeforeEach |
| void setUp() { |
| MockitoAnnotations.openMocks(this); |
| } |
| |
| @Test |
| void createComment_ShouldReturnCreatedComment() { |
| Comment newComment = new Comment(); |
| newComment.setUserid(1L); |
| newComment.setPostid(10); |
| newComment.setPostCommentcontent("这是一个评论"); |
| newComment.setCommenttime(LocalDateTime.now()); |
| |
| when(commentService.createComment(any(Comment.class))).thenReturn(newComment); |
| |
| Comment result = commentService.createComment(newComment); |
| |
| assertNotNull(result); |
| assertEquals("这是一个评论", result.getPostCommentcontent()); |
| verify(commentService).createComment(newComment); |
| } |
| |
| @Test |
| void deleteComment_ShouldReturnTrue() { |
| when(commentService.deleteComment(1)).thenReturn(true); |
| |
| boolean result = commentService.deleteComment(1); |
| |
| assertTrue(result); |
| verify(commentService).deleteComment(1); |
| } |
| |
| @Test |
| void updateComment_ShouldReturnTrue() { |
| Comment comment = new Comment(); |
| comment.setCommentid(1); |
| comment.setPostCommentcontent("更新的评论"); |
| |
| when(commentService.updateComment(comment)).thenReturn(true); |
| |
| boolean result = commentService.updateComment(comment); |
| |
| assertTrue(result); |
| verify(commentService).updateComment(comment); |
| } |
| |
| @Test |
| void getCommentsByPostId_ShouldReturnCommentsList() { |
| Comment comment = new Comment(); |
| comment.setPostid(10); |
| comment.setPostCommentcontent("测试评论"); |
| |
| when(commentService.getCommentsByPostId(10)).thenReturn(Collections.singletonList(comment)); |
| |
| List<Comment> result = commentService.getCommentsByPostId(10); |
| |
| assertEquals(1, result.size()); |
| assertEquals("测试评论", result.get(0).getPostCommentcontent()); |
| } |
| |
| @Test |
| void likeComment_ShouldReturnTrue() { |
| when(commentService.likeComment(1)).thenReturn(true); |
| |
| boolean result = commentService.likeComment(1); |
| |
| assertTrue(result); |
| verify(commentService).likeComment(1); |
| } |
| |
| @Test |
| void unlikeComment_ShouldReturnTrue() { |
| when(commentService.unlikeComment(1)).thenReturn(true); |
| |
| boolean result = commentService.unlikeComment(1); |
| |
| assertTrue(result); |
| verify(commentService).unlikeComment(1); |
| } |
| } |