blob: 9dedd29681617c184576d9cc61aa4b62aa6635d9 [file] [log] [blame]
223011381c359102025-06-03 15:19:59 +08001package com.example.myproject.controller;
2
3import com.example.myproject.entity.Comments;
4import com.example.myproject.entity.Users;
5import com.example.myproject.service.CommentService;
6import com.example.myproject.utils.Result;
7import org.junit.jupiter.api.BeforeEach;
8import org.junit.jupiter.api.Test;
9import org.mockito.*;
10import org.springframework.beans.factory.annotation.Autowired;
11
12import java.util.HashMap;
13import java.util.List;
14import java.util.Map;
15
16import static org.mockito.Mockito.*;
17import static org.junit.jupiter.api.Assertions.*;
18
19class 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}