Seamher | 0140612 | 2025-06-08 19:44:36 +0800 | [diff] [blame] | 1 | package com.g9.g9backend.controller; |
| 2 | |
| 3 | import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; |
| 4 | import com.baomidou.mybatisplus.extension.plugins.pagination.Page; |
| 5 | import com.g9.g9backend.pojo.Comment; |
| 6 | import com.g9.g9backend.pojo.DTO.GetCommentDTO; |
| 7 | import com.g9.g9backend.service.CommentService; |
| 8 | import org.junit.jupiter.api.Test; |
| 9 | import org.mockito.ArgumentMatchers; |
| 10 | import org.mockito.InjectMocks; |
| 11 | import org.mockito.Mock; |
| 12 | |
| 13 | import org.springframework.http.ResponseEntity; |
| 14 | |
| 15 | import java.util.Collections; |
| 16 | import java.util.Date; |
| 17 | |
| 18 | import static org.junit.jupiter.api.Assertions.*; |
| 19 | import static org.mockito.Mockito.*; |
| 20 | import static org.mockito.BDDMockito.given; |
| 21 | import org.junit.jupiter.api.extension.ExtendWith; |
| 22 | import org.mockito.junit.jupiter.MockitoExtension; |
| 23 | |
| 24 | @ExtendWith(MockitoExtension.class) |
| 25 | public class CommentControllerTest { |
| 26 | |
| 27 | @Mock |
| 28 | private CommentService commentService; |
| 29 | |
| 30 | @InjectMocks |
| 31 | private CommentController commentController; |
| 32 | |
| 33 | @Test |
| 34 | void testPostComment() { |
| 35 | Comment comment = new Comment(); |
| 36 | ResponseEntity<String> response = commentController.postComment(comment); |
| 37 | verify(commentService).save(comment); |
| 38 | assertEquals(200, response.getStatusCode().value()); |
| 39 | } |
| 40 | |
| 41 | @Test |
| 42 | void testDeleteComment() { |
| 43 | Integer id = 1; |
| 44 | ResponseEntity<String> response = commentController.deleteComment(id); |
| 45 | verify(commentService).removeById(id); |
| 46 | assertEquals(204, response.getStatusCode().value()); |
| 47 | } |
| 48 | |
| 49 | @Test |
| 50 | void testGetCommentWithResourceType() { |
| 51 | Comment comment = new Comment(); |
| 52 | comment.setCommentId(1); |
| 53 | comment.setUserId(2); |
| 54 | comment.setReplyId(null); |
| 55 | comment.setContent("Test"); |
| 56 | comment.setCreateAt(new Date()); |
| 57 | comment.setResourceId(1); |
| 58 | |
| 59 | Page<Comment> page = new Page<>(); |
| 60 | page.setRecords(Collections.singletonList(comment)); |
| 61 | |
| 62 | given(commentService.page(ArgumentMatchers.<Page<Comment>>any(), ArgumentMatchers.<LambdaQueryWrapper<Comment>>any())).willReturn(page); |
| 63 | |
| 64 | ResponseEntity<GetCommentDTO> response = commentController.getComment(1, 1, 10, "资源"); |
| 65 | assertEquals(200, response.getStatusCode().value()); |
| 66 | assertEquals(1, response.getBody().getRecords().size()); |
| 67 | } |
| 68 | } |