blob: c9ccce83cb353f963195add94ec373e7d64d0c8f [file] [log] [blame]
package com.example.g8backend.service;
import com.example.g8backend.entity.Post;
import com.example.g8backend.entity.PostLike;
import com.example.g8backend.mapper.PostMapper;
import com.example.g8backend.service.impl.PostServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
class PostLikeServiceTest {
@InjectMocks
private PostServiceImpl postService;
@Mock
private PostMapper postMapper;
private Post post;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this); // 初始化mock对象
post = new Post();
post.setPostId(1L);
post.setPostTitle("Test Post");
post.setPostContent("This is a test post.");
post.setUserId(1L);
}
// 测试点赞功能
@Test
void likePost_ShouldAddLike_WhenNotAlreadyLiked() {
Long userId = 1L;
Long postId = 1L;
// 设置返回值,模拟查询用户是否已点赞
when(postMapper.existsByUserIdAndPostId(userId, postId)).thenReturn(false);
// 调用点赞方法
postService.likePost(userId, postId);
// 验证postMapper的insert方法被调用一次,表示插入点赞记录
verify(postMapper, times(1)).insertLike(any(PostLike.class));
}
// 测试取消点赞功能
@Test
void unlikePost_ShouldRemoveLike_WhenAlreadyLiked() {
Long userId = 1L;
Long postId = 1L;
// 设置返回值,模拟查询用户是否已点赞
when(postMapper.existsByUserIdAndPostId(userId, postId)).thenReturn(true);
// 调用取消点赞方法
postService.unlikePost(userId, postId);
// 验证postMapper的deleteLikeByUserIdAndPostId方法被调用一次,表示删除点赞记录
verify(postMapper, times(1)).deleteLikeByUserIdAndPostId(userId, postId);
}
// 测试获取帖子点赞数功能
@Test
void getPostLikeCount_ShouldReturnCorrectCount() {
Long postId = 1L;
Long expectedCount = 10L;
// 模拟查询返回点赞数
when(postMapper.selectCount(postId)).thenReturn(expectedCount);
// 调用获取点赞数方法
Long actualCount = postService.getPostLikeCount(postId);
// 验证返回的点赞数是否正确
assertEquals(expectedCount, actualCount);
}
}