晓瑞223 | e046c3a | 2025-06-05 22:08:29 +0800 | [diff] [blame] | 1 | package edu.bjtu.groupone.backend; |
| 2 | |
| 3 | import edu.bjtu.groupone.backend.domain.entity.Post; |
| 4 | import edu.bjtu.groupone.backend.mapper.PostMapper; |
| 5 | import edu.bjtu.groupone.backend.service.impl.PostServiceImpl; |
| 6 | import org.junit.jupiter.api.BeforeEach; |
| 7 | import org.junit.jupiter.api.Test; |
| 8 | import org.junit.jupiter.api.extension.ExtendWith; |
| 9 | import org.mockito.InjectMocks; |
| 10 | import org.mockito.Mock; |
| 11 | import org.mockito.junit.jupiter.MockitoExtension; |
| 12 | |
| 13 | import java.util.Arrays; |
| 14 | import java.util.List; |
| 15 | |
| 16 | import static org.junit.jupiter.api.Assertions.assertEquals; |
| 17 | import static org.mockito.Mockito.*; |
| 18 | |
| 19 | @ExtendWith(MockitoExtension.class) |
| 20 | public class PostServiceTest { |
| 21 | |
| 22 | @Mock |
| 23 | private PostMapper postMapper; |
| 24 | |
| 25 | @InjectMocks |
| 26 | private PostServiceImpl postService; |
| 27 | |
| 28 | private Post post; |
| 29 | private List<Post> posts; |
| 30 | |
| 31 | @BeforeEach |
| 32 | void setUp() { |
| 33 | post = new Post(1L, 1, "测试帖子", "内容", "2023-06-15", 100); |
| 34 | posts = Arrays.asList(post); |
| 35 | } |
| 36 | |
| 37 | @Test |
| 38 | void addPost() { |
| 39 | doNothing().when(postMapper).insertPost(any(Post.class)); |
| 40 | |
| 41 | postService.addPost(post); |
| 42 | |
| 43 | verify(postMapper, times(1)).insertPost(post); |
| 44 | } |
| 45 | |
| 46 | @Test |
| 47 | void deletePost() { |
| 48 | doNothing().when(postMapper).deletePost(1L); |
| 49 | |
| 50 | postService.deletePost(1L); |
| 51 | |
| 52 | verify(postMapper, times(1)).deletePost(1L); |
| 53 | } |
| 54 | |
| 55 | @Test |
| 56 | void updatePost() { |
| 57 | doNothing().when(postMapper).updatePost(any(Post.class)); |
| 58 | |
| 59 | postService.updatePost(post); |
| 60 | |
| 61 | verify(postMapper, times(1)).updatePost(post); |
| 62 | } |
| 63 | |
| 64 | @Test |
| 65 | void getPostById() { |
| 66 | when(postMapper.selectPostById(1L)).thenReturn(post); |
| 67 | |
| 68 | Post result = postService.getPostById(1L); |
| 69 | |
| 70 | assertEquals(post, result); |
| 71 | } |
| 72 | |
| 73 | @Test |
| 74 | void getAllPosts() { |
| 75 | when(postMapper.selectAllPosts()).thenReturn(posts); |
| 76 | |
| 77 | List<Post> result = postService.getAllPosts(); |
| 78 | |
| 79 | assertEquals(posts, result); |
| 80 | } |
| 81 | } |