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