22301138 | f682451 | 2025-06-04 02:03:13 +0800 | [diff] [blame^] | 1 | package com.example.myproject.controller; |
| 2 | |
| 3 | import com.example.myproject.entity.Comments; |
| 4 | import com.example.myproject.entity.Users; |
| 5 | import com.example.myproject.service.CommentService; |
| 6 | import com.example.myproject.utils.Result; |
| 7 | import org.junit.jupiter.api.BeforeEach; |
| 8 | import org.junit.jupiter.api.Test; |
| 9 | import org.mockito.*; |
| 10 | import org.springframework.beans.factory.annotation.Autowired; |
| 11 | |
| 12 | import java.util.HashMap; |
| 13 | import java.util.List; |
| 14 | import java.util.Map; |
| 15 | |
| 16 | import static org.mockito.Mockito.*; |
| 17 | import static org.junit.jupiter.api.Assertions.*; |
| 18 | |
| 19 | class CommentControllerTest { |
| 20 | |
| 21 | @InjectMocks |
| 22 | private CommentController commentController; |
| 23 | @Mock |
| 24 | private CommentService commentService; |
| 25 | |
| 26 | @Mock |
| 27 | private Users mockUser; |
| 28 | |
| 29 | @BeforeEach |
| 30 | void setup() { |
| 31 | MockitoAnnotations.openMocks(this); |
| 32 | } |
| 33 | |
| 34 | // 测试添加评论 |
| 35 | @Test |
| 36 | void addCommentTest() { |
| 37 | Long postId = 1L; |
| 38 | Comments comment = new Comments(); |
| 39 | comment.setUserId(1L); |
| 40 | comment.setContent("This is a comment"); |
| 41 | comment.setParentComment(0L); |
| 42 | // 模拟服务层的行为 |
| 43 | doNothing().when(commentService).addComment(eq(postId), eq(comment)); |
| 44 | |
| 45 | // 调用控制器的方法 |
| 46 | String result = commentController.addComment(postId, comment); |
| 47 | |
| 48 | // 验证返回的结果 |
| 49 | assertEquals("Comment added successfully!", result); |
| 50 | |
| 51 | // 验证服务方法是否被调用 |
| 52 | verify(commentService, times(1)).addComment(eq(postId), eq(comment)); |
| 53 | } |
| 54 | |
| 55 | // 测试获取评论 |
| 56 | @Test |
| 57 | void getCommentsByPostIdTest() { |
| 58 | Long postId = 1L; |
| 59 | |
| 60 | // 模拟评论数据 |
| 61 | Map<String, Object> commentData = new HashMap<>(); |
| 62 | commentData.put("commentId", 1L); |
| 63 | commentData.put("content", "This is a comment"); |
| 64 | commentData.put("userId", 1L); |
| 65 | commentData.put("nickname", "user1"); |
| 66 | |
| 67 | // 模拟服务层的行为 |
| 68 | when(commentService.getCommentsByPostId(postId)).thenReturn(List.of(commentData)); |
| 69 | |
| 70 | // 调用控制器的方法 |
| 71 | List<Map<String, Object>> comments = commentController.getCommentsByPostId(postId); |
| 72 | |
| 73 | // 验证返回的评论数据 |
| 74 | assertEquals(1, comments.size()); |
| 75 | assertEquals("This is a comment", comments.get(0).get("content")); |
| 76 | assertEquals("user1", comments.get(0).get("nickname")); |
| 77 | |
| 78 | // 验证服务方法是否被调用 |
| 79 | verify(commentService, times(1)).getCommentsByPostId(postId); |
| 80 | } |
| 81 | } |