blob: bb768a0baa2dd94186669c7a8b8d228e109a8ebd [file] [log] [blame]
xiukirad0a7a082025-06-05 16:28:08 +08001package com.g9.g9backend.controller;
2
xiukira07ea6ee2025-06-06 19:28:24 +08003import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
4import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
xiukirad0a7a082025-06-05 16:28:08 +08005import com.fasterxml.jackson.databind.ObjectMapper;
6import com.g9.g9backend.pojo.*;
7import com.g9.g9backend.pojo.DTO.*;
8import com.g9.g9backend.service.*;
9import org.junit.jupiter.api.BeforeEach;
10import org.junit.jupiter.api.Test;
11import org.mockito.InjectMocks;
12import org.mockito.Mock;
13import org.mockito.MockitoAnnotations;
14import org.springframework.http.MediaType;
15import org.springframework.test.web.servlet.MockMvc;
16import org.springframework.test.web.servlet.setup.MockMvcBuilders;
17
xiukira07ea6ee2025-06-06 19:28:24 +080018import java.util.ArrayList;
19import java.util.Date;
20import java.util.List;
21
xiukirad0a7a082025-06-05 16:28:08 +080022import static org.mockito.ArgumentMatchers.*;
23import static org.mockito.Mockito.when;
24import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
25import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
26
27public class UserControllerTest {
28
29 private MockMvc mockMvc;
30
31 @InjectMocks
32 private UserController userController;
33
34 @Mock
35 private UserService userService;
36
37 @Mock
38 private InvitationService invitationService;
39
40 @Mock
41 private SubscriptionService subscriptionService;
42
xiukira29f8d372025-06-06 18:07:13 +080043 @Mock
44 private SearchHistoryService searchHistoryService;
45
xiukira07ea6ee2025-06-06 19:28:24 +080046 @Mock
47 private RewardService rewardService;
48
49 @Mock
50 private UserCollectionService userCollectionService;
51
52 @Mock
53 private UserUploadService userUploadService;
54
55 @Mock
56 private UserPurchaseService userPurchaseService;
57
58 @Mock
59 private ResourceService resourceService;
60
xiukiraac78f3d2025-06-08 23:38:10 +080061 @Mock
62 private ThreadService threadService;
63
xiukirad0a7a082025-06-05 16:28:08 +080064 private final ObjectMapper objectMapper = new ObjectMapper();
65
66 @BeforeEach
67 public void setup() {
68 MockitoAnnotations.openMocks(this);
69 mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
70 }
71
72 // 注册
73 @Test
74 public void testRegister_success() throws Exception {
75 /*
76 注意单元测试中(使用Mockito ),当多次为同一个方法设置不同的返回值时,后面的设置会覆盖前面的设置
77 可见单元测试在执行时,本质上在跑实际接口实现,当遇到被mock模拟的方法时,会来测试代码里找对应的when...thenReturn,直接看最后一个设置,所以当测试方法时,测试代码里写的和实际接口的顺序上不是一一对应
78 而是测试代码里写B C A,实际接口代码里写A B C,当实际代码跑到A时去测试代码里从后往前找到A,而不是看测试代码里第一个是不是A若是再用的逻辑
79 所以如果写成如下形式:
80 when(userService.getOne(any())).thenReturn(null);
81 ....其他代码
82 when(userService.getOne(any())).thenReturn(new User(2, "hcy", "123", null, 0, 0, null, 0, 0, 0));
83 则下面的设置会覆盖上面的设置,导致无论什么时候调用该方法,返回的都是非空对象
84 所以应该写成如下形式:
85 when(userService.getOne(any()))
86 .thenReturn(null) // 第一次调用返回null
87 .thenReturn(new User(2, "hcy", "123", null, 0, 0, null, 0, 0, 0)); // 第二次调用返回非空对象
88 */
89
90 when(userService.getOne(any()))
91 .thenReturn(null) // 第一次调用返回null,表示用户名不是已存在的
92 .thenReturn(new User(2, "hcy", "123", null, 0, 0, null, 0, 0, 0)); // 第二次调用返回非空对象,表示获取添加后的用户信息
93 // 邀请码存在且未被使用
94 when(invitationService.getOne(any())).thenReturn(new Invitation("6RCA7Y8J", 1, 0));
95 // 添加新用户
96 when(userService.save(any())).thenReturn(true);
97 // 设置该邀请码被新添加的新用户使用
98 when(invitationService.update(any())).thenReturn(true);
99 // 获取五个新邀请码
100 when(invitationService.generateInvitationCode()).thenReturn(new String[5]);
101 // 分配给新用户邀请码
102 when(invitationService.save(any())).thenReturn(true);
103 mockMvc.perform(post("/user/register")
104 .contentType(MediaType.APPLICATION_JSON)
105 .content(objectMapper.writeValueAsString(new RegisterDTO("hcy", "123", "6RCA7Y8J"))))
106 .andExpect(status().isOk());
107 }
108
109 @Test
110 public void testRegister_userExists() throws Exception {
111 // 用户名不是已存在的
112 when(userService.getOne(any())).thenReturn(new User(2, "hcy", "123", null, 0, 0, null, 0, 0, 0));
113 mockMvc.perform(post("/user/register")
114 .contentType(MediaType.APPLICATION_JSON)
115 .content(objectMapper.writeValueAsString(new RegisterDTO("hcy", "123", "6RCA7Y8J"))))
xiukirab8bd04e2025-06-09 17:31:16 +0800116 .andExpect(status().is(412));
xiukirad0a7a082025-06-05 16:28:08 +0800117 }
118
119 @Test
120 public void testRegister_invitationNotExist() throws Exception {
121 // 用户名不是已存在的
122 when(userService.getOne(any())).thenReturn(null);
123 // 邀请码不存在
124 when(invitationService.getOne(any())).thenReturn(null);
125 mockMvc.perform(post("/user/register")
126 .contentType(MediaType.APPLICATION_JSON)
127 .content(objectMapper.writeValueAsString(new RegisterDTO("hcy", "123", "6RCA7Y8J"))))
128 .andExpect(status().is(409));
129 }
130
131 @Test
132 public void testRegister_invitationUsed() throws Exception {
133 // 用户名不是已存在的
134 when(userService.getOne(any())).thenReturn(null);
135 // 邀请码存在但已被使用
136 when(invitationService.getOne(any())).thenReturn(new Invitation("6RCA7Y8J", 1, 2));
137 mockMvc.perform(post("/user/register")
138 .contentType(MediaType.APPLICATION_JSON)
139 .content(objectMapper.writeValueAsString(new RegisterDTO("hcy", "123", "6RCA7Y8J"))))
140 .andExpect(status().is(410));
141 }
142
143 // 登录
144 @Test
145 public void testLogin_success() throws Exception {
146 // 设置请求参数
147 User user = new User();
148 user.setUsername("hcy");
149 user.setPassword("123");
150
151 when(userService.getOne(any())).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
152
153 mockMvc.perform(post("/user/login")
154 .contentType(MediaType.APPLICATION_JSON)
155 .content(objectMapper.writeValueAsString(user)))
156 .andExpect(status().isOk());
157 }
158
159 @Test
160 public void testLogin_userNotFound() throws Exception {
161 //设置请求参数
162 User user = new User();
163 user.setUsername("hcy");
164 user.setPassword("123");
165
166 when(userService.getOne(any())).thenReturn(null);
167
168 mockMvc.perform(post("/user/login")
169 .contentType(MediaType.APPLICATION_JSON)
170 .content(objectMapper.writeValueAsString(user)))
171 .andExpect(status().is(406));
172 }
173
174 @Test
175 public void testLogin_wrongPassword() throws Exception {
176 // 设置请求参数
177 User user = new User();
178 user.setUsername("hcy");
179 user.setPassword("wrongPassword");
180
181 when(userService.getOne(any())).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
182
183 mockMvc.perform(post("/user/login")
184 .contentType(MediaType.APPLICATION_JSON)
185 .content(objectMapper.writeValueAsString(user)))
186 .andExpect(status().is(408));
187 }
188
189 // 关注
190 @Test
191 public void testSubscription() throws Exception {
192 when(subscriptionService.save(any())).thenReturn(true);
193
194 mockMvc.perform(post("/user/subscription")
195 .contentType(MediaType.APPLICATION_JSON)
196 .content(objectMapper.writeValueAsString(new Subscription(1, 2))))
197 .andExpect(status().isOk());
198 }
xiukira29f8d372025-06-06 18:07:13 +0800199
200 // 注销
201 @Test
202 public void testUserDelete_success() throws Exception {
203
204 when(userService.getOne(any())).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
205
206 mockMvc.perform(delete("/user")
207 .param("userId", "1")
208 .param("password", "123"))
209 .andExpect(status().isNoContent());
210 }
211
212 @Test
213 public void testUserDelete_wrongPassword() throws Exception {
214
215 when(userService.getOne(any())).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
216
217 mockMvc.perform(delete("/user")
218 .param("userId", "1")
219 .param("password", "wrong"))
220 .andExpect(status().is(408));
221 }
222
223 // 删除搜索历史
224 @Test
225 public void testSearchDelete() throws Exception {
226
227 when(searchHistoryService.removeById(anyInt())).thenReturn(true);
228
229 mockMvc.perform(delete("/user/search")
230 .param("searchHistoryId", "1"))
231 .andExpect(status().isNoContent());
232 }
233
234 // 取消关注
235 @Test
236 public void testSubscriptionDelete() throws Exception {
237
238 when(subscriptionService.remove(any())).thenReturn(true);
239
240 mockMvc.perform(delete("/user/subscription")
241 .param("userId", "1")
242 .param("followerId", "2"))
243 .andExpect(status().isNoContent());
244 }
xiukira07ea6ee2025-06-06 19:28:24 +0800245
246 // 获取用户ID
247 @Test
248 public void testGetUserId() throws Exception {
249
250 when(userService.getOne(any())).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
251
252 mockMvc.perform(get("/user/getId")
253 .param("username", "hcy")
254 .param("password", "123"))
255 .andExpect(status().isOk());
256 }
257
258 // 获取邀请码
259 @Test
260 public void testGetInvitationCode() throws Exception {
261
262 List<Invitation> invitationList = new ArrayList<>();
263 invitationList.add(new Invitation("1RCA7Y8J", 0, 0));
264 invitationList.add(new Invitation("2RCA7Y8J", 0, 0));
265 invitationList.add(new Invitation("3RCA7Y8J", 0, 0));
266 invitationList.add(new Invitation("4RCA7Y8J", 0, 0));
267 invitationList.add(new Invitation("5RCA7Y8J", 0, 0));
268
269 QueryWrapper<Invitation> invitationQuery = new QueryWrapper<>();
270 invitationQuery.eq("user_id", 1).eq("invitee_id", 0);
271 invitationQuery.select("invitation_code");
272
273 when(invitationService.list(invitationQuery)).thenReturn(invitationList); //这里用any()无法识别,因为list有多种参数可能
274
275 mockMvc.perform(get("/user/invitation-code")
276 .param("userId", "1"))
277 .andExpect(status().isOk());
278 }
279
280 // 获取用户信息
281 @Test
282 public void testGetUserInfo() throws Exception {
283
284 when(userService.getById(anyInt())).thenReturn(new User(1, "user", "pass", null, 0, 0, null, 0, 0, 0));
285
286 mockMvc.perform(get("/user/info")
287 .param("userId", "1"))
288 .andExpect(status().isOk());
289 }
290
291 // 获取悬赏
292 @Test
293 public void testGetUserReward() throws Exception {
294
295 when(rewardService.page(any(), any())).thenReturn(new Page<>(1, 2));
296
297 mockMvc.perform(get("/user/reward")
298 .param("userId", "1")
299 .param("pageNumber", "2")
300 .param("rows", "2"))
301 .andExpect(status().isOk());
302 }
303
304 // 获取收藏
305 @Test
306 public void testGetUserCollection() throws Exception {
307
308 when(userCollectionService.page(any(), any())).thenReturn(new Page<>(1, 2));
xiukiraac78f3d2025-06-08 23:38:10 +0800309 when(resourceService.getById(anyInt())).thenReturn(new Resource(1, "a", null, null, null, new Date(), new Date(), 100, 0, 0, 0, 0, "mod"));
xiukira07ea6ee2025-06-06 19:28:24 +0800310
311 mockMvc.perform(get("/user/collection")
312 .param("userId", "1")
313 .param("pageNumber", "1")
314 .param("rows", "2"))
315 .andExpect(status().isOk());
316 }
317
318 // 获取上传
319 @Test
320 public void testGetUserUpload() throws Exception {
321
322 when(userUploadService.page(any(), any())).thenReturn(new Page<>(1, 2));
xiukiraac78f3d2025-06-08 23:38:10 +0800323 when(resourceService.getById(anyInt())).thenReturn(new Resource(1, "a", null, null, null, new Date(), new Date(), 100, 0, 0, 0, 0, "mod"));
xiukira07ea6ee2025-06-06 19:28:24 +0800324
325 mockMvc.perform(get("/user/upload")
326 .param("userId", "1")
327 .param("pageNumber", "1")
328 .param("rows", "2"))
329 .andExpect(status().isOk());
330 }
331
332 // 获取购买
333 @Test
334 public void testGetUserPurchase() throws Exception {
335
336 when(userPurchaseService.page(any(), any())).thenReturn(new Page<>(1, 2));
xiukiraac78f3d2025-06-08 23:38:10 +0800337 when(resourceService.getById(anyInt())).thenReturn(new Resource(1, "a", null, null, null, new Date(), new Date(), 100, 0, 0, 0, 0, "mod"));
xiukira07ea6ee2025-06-06 19:28:24 +0800338
339 mockMvc.perform(get("/user/purchase")
340 .param("userId", "1")
341 .param("pageNumber", "1")
342 .param("rows", "2"))
343 .andExpect(status().isOk());
344 }
345
346 // 获取搜索历史
347 @Test
348 public void testGetUserSearchHistory() throws Exception {
349
350 List<SearchHistory> searchHistoryList = new ArrayList<>();
351
352 QueryWrapper<SearchHistory> searchHistoryQuery = new QueryWrapper<>();
353 searchHistoryQuery.eq("user_id", 1).orderByDesc("search_history_id").last("LIMIT 10");
354
355 when(searchHistoryService.list(searchHistoryQuery)).thenReturn(searchHistoryList);
356
357 mockMvc.perform(get("/user/search")
358 .param("userId", "1"))
359 .andExpect(status().isOk());
360 }
361
xiukiraac78f3d2025-06-08 23:38:10 +0800362 // 获取发布过的贴子
363 @Test
364 public void testGetUserThread() throws Exception {
365
366 when(threadService.page(any(), any())).thenReturn(new Page<>(1, 2));
367
368 mockMvc.perform(get("/user/thread")
369 .param("userId", "1")
370 .param("pageNumber", "1")
371 .param("rows", "2"))
372 .andExpect(status().isOk());
373 }
374
xiukira07ea6ee2025-06-06 19:28:24 +0800375 // 获取用户数据
376 @Test
377 public void testGetUserData() throws Exception {
378
379 when(userService.getById(1)).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
380
381 List<UserUpload> UserUpload = new ArrayList<>();
382 QueryWrapper<UserUpload> userUploadQuery = new QueryWrapper<>();
383 userUploadQuery.eq("user_id", 1);
384 when(userUploadService.list(userUploadQuery)).thenReturn(UserUpload);
385
386 when(resourceService.getById(anyInt())).thenReturn(new Resource());
387
388 mockMvc.perform(get("/user/data")
389 .param("userId", "1"))
390 .andExpect(status().isOk());
391 }
392
393 // 获取关注列表
394 @Test
395 public void testGetUserSubscriber() throws Exception {
396
397 QueryWrapper<Subscription> subscriptionQuery = new QueryWrapper<>();
398 subscriptionQuery.eq("follower_id", 1);
399 List<Subscription> subscriptionList = new ArrayList<>();
400
401 when(subscriptionService.list(subscriptionQuery)).thenReturn(subscriptionList);
402 when(userService.getById(1)).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
403
404 mockMvc.perform(get("/user/subscriber")
405 .param("userId", "1"))
406 .andExpect(status().isOk());
407 }
408
409 // 获取粉丝列表
410 @Test
411 public void testGetUserFollower() throws Exception {
412
413 QueryWrapper<Subscription> subscriptionQuery = new QueryWrapper<>();
414 subscriptionQuery.eq("user_id", 1);
415 List<Subscription> subscriptionList = new ArrayList<>();
416
417 when(subscriptionService.list(subscriptionQuery)).thenReturn(subscriptionList);
418 when(userService.getById(1)).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
419
420 mockMvc.perform(get("/user/follower")
421 .param("userId", "1"))
422 .andExpect(status().isOk());
423 }
xiukiraa3c84182025-06-06 20:54:38 +0800424
425 // 修改签名
426 @Test
427 public void testModifySignature() throws Exception {
428
429 User user = new User();
430 user.setUserId(1);
431 user.setSignature("New Signature");
432
433 when(userService.update(any())).thenReturn(true);
434
435 mockMvc.perform(put("/user/signature")
436 .contentType(MediaType.APPLICATION_JSON)
437 .content(objectMapper.writeValueAsString(user)))
438 .andExpect(status().isOk());
439 }
440
441 // 修改密码
442 @Test
443 public void testModifyPassword_success() throws Exception {
444
445 // 密码正确
446 when(userService.getOne(any())).thenReturn(new User(1, "hcy", "oldPass", null, 0, 0, null, 0, 0, 0));
447 when(userService.update(any())).thenReturn(true);
448
449 mockMvc.perform(put("/user/password")
450 .contentType(MediaType.APPLICATION_JSON)
451 .content(objectMapper.writeValueAsString(new ModifyPasswordDTO(1, "oldPass", "newPass"))))
452 .andExpect(status().isOk());
453 }
454
455 @Test
456 public void testModifyPassword_wrongPassword() throws Exception {
457
458 // 密码错误
459 when(userService.getOne(any())).thenReturn(new User(1, "hcy", "oldPass", null, 0, 0, null, 0, 0, 0));
460
461 mockMvc.perform(put("/user/password")
462 .contentType(MediaType.APPLICATION_JSON)
463 .content(objectMapper.writeValueAsString(new ModifyPasswordDTO(1, "wrongPassword", "newPass"))))
464 .andExpect(status().is(408));
465 }
466
467 // 修改头像
468 @Test
469 public void testModifyAvatar() throws Exception {
470
471 // 设置请求参数
472 User user = new User();
473 user.setUserId(1);
474 user.setAvatar("avatar.png");
475
476 when(userService.update(any())).thenReturn(true);
477
478 mockMvc.perform(put("/user/avatar")
479 .contentType(MediaType.APPLICATION_JSON)
480 .content(objectMapper.writeValueAsString(user)))
481 .andExpect(status().isOk());
482 }
xiukirad0a7a082025-06-05 16:28:08 +0800483}