| package edu.bjtu.groupone.backend; |
| |
| import edu.bjtu.groupone.backend.domain.entity.Post; |
| import edu.bjtu.groupone.backend.mapper.PostMapper; |
| import edu.bjtu.groupone.backend.service.impl.PostServiceImpl; |
| import org.junit.jupiter.api.BeforeEach; |
| import org.junit.jupiter.api.Test; |
| import org.junit.jupiter.api.extension.ExtendWith; |
| import org.mockito.InjectMocks; |
| import org.mockito.Mock; |
| import org.mockito.junit.jupiter.MockitoExtension; |
| |
| import java.util.Arrays; |
| import java.util.List; |
| |
| import static org.junit.jupiter.api.Assertions.assertEquals; |
| import static org.mockito.Mockito.*; |
| |
| @ExtendWith(MockitoExtension.class) |
| public class PostServiceTest { |
| |
| @Mock |
| private PostMapper postMapper; |
| |
| @InjectMocks |
| private PostServiceImpl postService; |
| |
| private Post post; |
| private List<Post> posts; |
| |
| @BeforeEach |
| void setUp() { |
| post = new Post(1L, 1, "测试帖子", "内容", "2023-06-15", 100); |
| posts = Arrays.asList(post); |
| } |
| |
| @Test |
| void addPost() { |
| doNothing().when(postMapper).insertPost(any(Post.class)); |
| |
| postService.addPost(post); |
| |
| verify(postMapper, times(1)).insertPost(post); |
| } |
| |
| @Test |
| void deletePost() { |
| doNothing().when(postMapper).deletePost(1L); |
| |
| postService.deletePost(1L); |
| |
| verify(postMapper, times(1)).deletePost(1L); |
| } |
| |
| @Test |
| void updatePost() { |
| doNothing().when(postMapper).updatePost(any(Post.class)); |
| |
| postService.updatePost(post); |
| |
| verify(postMapper, times(1)).updatePost(post); |
| } |
| |
| @Test |
| void getPostById() { |
| when(postMapper.selectPostById(1L)).thenReturn(post); |
| |
| Post result = postService.getPostById(1L); |
| |
| assertEquals(post, result); |
| } |
| |
| @Test |
| void getAllPosts() { |
| when(postMapper.selectAllPosts()).thenReturn(posts); |
| |
| List<Post> result = postService.getAllPosts(); |
| |
| assertEquals(posts, result); |
| } |
| } |