21301050 | f5f827d | 2025-06-09 15:09:33 +0800 | [diff] [blame^] | 1 | package com.pt5.pthouduan.ControllerTest; |
| 2 | |
| 3 | import com.pt5.pthouduan.controller.RecommendController; |
| 4 | import com.pt5.pthouduan.entity.Torrent; |
| 5 | import com.pt5.pthouduan.service.RecommendService; |
| 6 | import org.junit.jupiter.api.BeforeEach; |
| 7 | import org.junit.jupiter.api.Test; |
| 8 | import org.mockito.InjectMocks; |
| 9 | import org.mockito.Mock; |
| 10 | import org.mockito.MockitoAnnotations; |
| 11 | |
| 12 | import java.util.Arrays; |
| 13 | import java.util.List; |
| 14 | |
| 15 | import static org.junit.jupiter.api.Assertions.*; |
| 16 | import static org.mockito.ArgumentMatchers.anyLong; |
| 17 | import static org.mockito.Mockito.*; |
| 18 | |
| 19 | class RecommendControllerTest { |
| 20 | |
| 21 | @Mock |
| 22 | private RecommendService recommendService; |
| 23 | |
| 24 | @InjectMocks |
| 25 | private RecommendController recommendController; |
| 26 | |
| 27 | @BeforeEach |
| 28 | void setUp() { |
| 29 | MockitoAnnotations.openMocks(this); |
| 30 | } |
| 31 | |
| 32 | @Test |
| 33 | void getRecommendList_Success() { |
| 34 | // 准备测试数据 |
| 35 | Torrent torrent1 = new Torrent(); |
| 36 | |
| 37 | // 执行测试 |
| 38 | List<Torrent> actualList = recommendController.getRecommendList(123L); |
| 39 | |
| 40 | // 验证结果 |
| 41 | verify(recommendService, times(1)).recommendForUser(123L); |
| 42 | } |
| 43 | |
| 44 | @Test |
| 45 | void getRecommendList_EmptyList() { |
| 46 | // 模拟空列表返回 |
| 47 | when(recommendService.recommendForUser(anyLong())) |
| 48 | .thenReturn(List.of()); |
| 49 | |
| 50 | List<Torrent> result = recommendController.getRecommendList(456L); |
| 51 | |
| 52 | assertTrue(result.isEmpty()); |
| 53 | } |
| 54 | |
| 55 | @Test |
| 56 | void getRecommendList_InvalidUserId() { |
| 57 | // 模拟无效用户ID情况 |
| 58 | when(recommendService.recommendForUser(-1L)) |
| 59 | .thenThrow(new IllegalArgumentException("Invalid user ID")); |
| 60 | |
| 61 | assertThrows(IllegalArgumentException.class, () -> { |
| 62 | recommendController.getRecommendList(-1L); |
| 63 | }); |
| 64 | } |
| 65 | |
| 66 | @Test |
| 67 | void getRecommendList_ServiceException() { |
| 68 | // 模拟服务层异常 |
| 69 | when(recommendService.recommendForUser(anyLong())) |
| 70 | .thenThrow(new RuntimeException("Recommendation service unavailable")); |
| 71 | |
| 72 | assertThrows(RuntimeException.class, () -> { |
| 73 | recommendController.getRecommendList(999L); |
| 74 | }); |
| 75 | } |
| 76 | } |