夜雨声烦 | 0206359 | 2025-04-23 18:10:00 +0800 | [diff] [blame] | 1 | package com.example.g8backend.service; |
| 2 | |
| 3 | import com.example.g8backend.entity.Post; |
| 4 | import com.example.g8backend.entity.PostLike; |
| 5 | import com.example.g8backend.mapper.PostMapper; |
| 6 | import com.example.g8backend.service.impl.PostServiceImpl; |
| 7 | import org.junit.jupiter.api.BeforeEach; |
| 8 | import org.junit.jupiter.api.Test; |
| 9 | import org.mockito.InjectMocks; |
| 10 | import org.mockito.Mock; |
| 11 | import org.mockito.MockitoAnnotations; |
| 12 | |
| 13 | import static org.mockito.Mockito.*; |
| 14 | |
| 15 | import static org.junit.jupiter.api.Assertions.*; |
| 16 | |
| 17 | class PostLikeServiceTest { |
| 18 | |
| 19 | @InjectMocks |
| 20 | private PostServiceImpl postService; |
| 21 | |
| 22 | @Mock |
| 23 | private PostMapper postMapper; |
| 24 | |
| 25 | private Post post; |
| 26 | |
| 27 | @BeforeEach |
| 28 | void setUp() { |
| 29 | MockitoAnnotations.openMocks(this); // 初始化mock对象 |
| 30 | post = new Post(); |
| 31 | post.setPostId(1L); |
| 32 | post.setPostTitle("Test Post"); |
| 33 | post.setPostContent("This is a test post."); |
| 34 | post.setUserId(1L); |
| 35 | } |
| 36 | |
| 37 | // 测试点赞功能 |
| 38 | @Test |
| 39 | void likePost_ShouldAddLike_WhenNotAlreadyLiked() { |
| 40 | Long userId = 1L; |
| 41 | Long postId = 1L; |
| 42 | |
| 43 | // 设置返回值,模拟查询用户是否已点赞 |
| 44 | when(postMapper.existsByUserIdAndPostId(userId, postId)).thenReturn(false); |
| 45 | |
| 46 | // 调用点赞方法 |
| 47 | postService.likePost(userId, postId); |
| 48 | |
| 49 | // 验证postMapper的insert方法被调用一次,表示插入点赞记录 |
wuchimedes | 191df94 | 2025-06-08 11:03:37 +0800 | [diff] [blame^] | 50 | verify(postMapper, times(1)).insertLike(any(PostLike.class)); |
夜雨声烦 | 0206359 | 2025-04-23 18:10:00 +0800 | [diff] [blame] | 51 | } |
| 52 | |
| 53 | // 测试取消点赞功能 |
| 54 | @Test |
| 55 | void unlikePost_ShouldRemoveLike_WhenAlreadyLiked() { |
| 56 | Long userId = 1L; |
| 57 | Long postId = 1L; |
| 58 | |
| 59 | // 设置返回值,模拟查询用户是否已点赞 |
| 60 | when(postMapper.existsByUserIdAndPostId(userId, postId)).thenReturn(true); |
| 61 | |
| 62 | // 调用取消点赞方法 |
| 63 | postService.unlikePost(userId, postId); |
| 64 | |
| 65 | // 验证postMapper的deleteLikeByUserIdAndPostId方法被调用一次,表示删除点赞记录 |
| 66 | verify(postMapper, times(1)).deleteLikeByUserIdAndPostId(userId, postId); |
| 67 | } |
| 68 | |
| 69 | // 测试获取帖子点赞数功能 |
| 70 | @Test |
| 71 | void getPostLikeCount_ShouldReturnCorrectCount() { |
| 72 | Long postId = 1L; |
| 73 | Long expectedCount = 10L; |
| 74 | |
| 75 | // 模拟查询返回点赞数 |
| 76 | when(postMapper.selectCount(postId)).thenReturn(expectedCount); |
| 77 | |
| 78 | // 调用获取点赞数方法 |
| 79 | Long actualCount = postService.getPostLikeCount(postId); |
| 80 | |
| 81 | // 验证返回的点赞数是否正确 |
| 82 | assertEquals(expectedCount, actualCount); |
| 83 | } |
| 84 | } |