晓瑞223 | e046c3a | 2025-06-05 22:08:29 +0800 | [diff] [blame] | 1 | package edu.bjtu.groupone.backend; |
| 2 | |
| 3 | import edu.bjtu.groupone.backend.domain.entity.Comment; |
| 4 | import edu.bjtu.groupone.backend.mapper.CommentMapper; |
| 5 | import edu.bjtu.groupone.backend.service.impl.CommentServiceImpl; |
| 6 | import org.junit.jupiter.api.BeforeEach; |
| 7 | import org.junit.jupiter.api.Test; |
| 8 | import org.junit.jupiter.api.extension.ExtendWith; |
| 9 | import org.mockito.InjectMocks; |
| 10 | import org.mockito.Mock; |
| 11 | import org.mockito.junit.jupiter.MockitoExtension; |
| 12 | |
| 13 | import java.util.Arrays; |
| 14 | import java.util.List; |
| 15 | |
| 16 | import static org.junit.jupiter.api.Assertions.assertEquals; |
| 17 | import static org.mockito.Mockito.*; |
| 18 | |
| 19 | @ExtendWith(MockitoExtension.class) |
| 20 | public class CommentServiceTest { |
| 21 | |
| 22 | @Mock |
| 23 | private CommentMapper commentMapper; |
| 24 | |
| 25 | @InjectMocks |
| 26 | private CommentServiceImpl commentService; |
| 27 | |
| 28 | private Comment comment; |
| 29 | private List<Comment> comments; |
| 30 | |
| 31 | @BeforeEach |
| 32 | void setUp() { |
| 33 | comment = new Comment(1L, 1L, 1, "测试评论", "2023-06-15"); |
| 34 | comments = Arrays.asList(comment); |
| 35 | } |
| 36 | |
| 37 | @Test |
| 38 | void addComment() { |
| 39 | doNothing().when(commentMapper).insertComment(any(Comment.class)); |
| 40 | |
| 41 | commentService.addComment(comment); |
| 42 | |
| 43 | verify(commentMapper, times(1)).insertComment(comment); |
| 44 | } |
| 45 | |
| 46 | @Test |
| 47 | void deleteComment() { |
| 48 | doNothing().when(commentMapper).deleteComment(1L); |
| 49 | |
| 50 | commentService.deleteComment(1L); |
| 51 | |
| 52 | verify(commentMapper, times(1)).deleteComment(1L); |
| 53 | } |
| 54 | |
| 55 | @Test |
| 56 | void updateComment() { |
| 57 | doNothing().when(commentMapper).updateComment(any(Comment.class)); |
| 58 | |
| 59 | commentService.updateComment(comment); |
| 60 | |
| 61 | verify(commentMapper, times(1)).updateComment(comment); |
| 62 | } |
| 63 | |
| 64 | @Test |
| 65 | void getCommentById() { |
| 66 | when(commentMapper.selectCommentById(1L)).thenReturn(comment); |
| 67 | |
| 68 | Comment result = commentService.getCommentById(1L); |
| 69 | |
| 70 | assertEquals(comment, result); |
| 71 | } |
| 72 | |
| 73 | @Test |
| 74 | void getCommentsByPostId() { |
| 75 | when(commentMapper.selectCommentsByPostId(1L)).thenReturn(comments); |
| 76 | |
| 77 | List<Comment> result = commentService.getCommentsByPostId(1L); |
| 78 | |
| 79 | assertEquals(comments, result); |
| 80 | } |
| 81 | } |