blob: 9dedd29681617c184576d9cc61aa4b62aa6635d9 [file] [log] [blame]
package com.example.myproject.controller;
import com.example.myproject.entity.Comments;
import com.example.myproject.entity.Users;
import com.example.myproject.service.CommentService;
import com.example.myproject.utils.Result;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
class CommentControllerTest {
@InjectMocks
private CommentController commentController;
@Mock
private CommentService commentService;
@Mock
private Users mockUser;
@BeforeEach
void setup() {
MockitoAnnotations.openMocks(this);
}
// 测试添加评论
@Test
void addCommentTest() {
Long postId = 1L;
Comments comment = new Comments();
comment.setUserId(1L);
comment.setContent("This is a comment");
comment.setParentComment(0L);
// 模拟服务层的行为
doNothing().when(commentService).addComment(eq(postId), eq(comment));
// 调用控制器的方法
String result = commentController.addComment(postId, comment);
// 验证返回的结果
assertEquals("Comment added successfully!", result);
// 验证服务方法是否被调用
verify(commentService, times(1)).addComment(eq(postId), eq(comment));
}
// 测试获取评论
@Test
void getCommentsByPostIdTest() {
Long postId = 1L;
// 模拟评论数据
Map<String, Object> commentData = new HashMap<>();
commentData.put("commentId", 1L);
commentData.put("content", "This is a comment");
commentData.put("userId", 1L);
commentData.put("nickname", "user1");
// 模拟服务层的行为
when(commentService.getCommentsByPostId(postId)).thenReturn(List.of(commentData));
// 调用控制器的方法
List<Map<String, Object>> comments = commentController.getCommentsByPostId(postId);
// 验证返回的评论数据
assertEquals(1, comments.size());
assertEquals("This is a comment", comments.get(0).get("content"));
assertEquals("user1", comments.get(0).get("nickname"));
// 验证服务方法是否被调用
verify(commentService, times(1)).getCommentsByPostId(postId);
}
}