houzhongyi
2024-07-11 e7c1260db32209a078a962aaa0ad5492c35774fb
提交 | 用户 | 时间
e7c126 1 package com.iailab.module.system.service.user;
H 2
3 import cn.hutool.core.util.RandomUtil;
4 import com.iailab.framework.common.enums.CommonStatusEnum;
5 import com.iailab.framework.common.exception.ServiceException;
6 import com.iailab.framework.common.pojo.PageResult;
7 import com.iailab.framework.common.util.collection.ArrayUtils;
8 import com.iailab.framework.common.util.collection.CollectionUtils;
9 import com.iailab.framework.test.core.ut.BaseDbUnitTest;
10 import com.iailab.module.infra.api.file.FileApi;
11 import com.iailab.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO;
12 import com.iailab.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO;
13 import com.iailab.module.system.controller.admin.user.vo.user.UserImportExcelVO;
14 import com.iailab.module.system.controller.admin.user.vo.user.UserImportRespVO;
15 import com.iailab.module.system.controller.admin.user.vo.user.UserPageReqVO;
16 import com.iailab.module.system.controller.admin.user.vo.user.UserSaveReqVO;
17 import com.iailab.module.system.dal.dataobject.dept.DeptDO;
18 import com.iailab.module.system.dal.dataobject.dept.PostDO;
19 import com.iailab.module.system.dal.dataobject.dept.UserPostDO;
20 import com.iailab.module.system.dal.dataobject.tenant.TenantDO;
21 import com.iailab.module.system.dal.dataobject.user.AdminUserDO;
22 import com.iailab.module.system.dal.mysql.dept.UserPostMapper;
23 import com.iailab.module.system.dal.mysql.user.AdminUserMapper;
24 import com.iailab.module.system.enums.common.SexEnum;
25 import com.iailab.module.system.service.dept.DeptService;
26 import com.iailab.module.system.service.dept.PostService;
27 import com.iailab.module.system.service.permission.PermissionService;
28 import com.iailab.module.system.service.tenant.TenantService;
29 import org.junit.jupiter.api.Test;
30 import org.mockito.stubbing.Answer;
31 import org.springframework.boot.test.mock.mockito.MockBean;
32 import org.springframework.context.annotation.Import;
33 import org.springframework.security.crypto.password.PasswordEncoder;
34
35 import javax.annotation.Resource;
36 import java.io.ByteArrayInputStream;
37 import java.util.Collection;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.function.Consumer;
41
42 import static cn.hutool.core.util.RandomUtil.randomBytes;
43 import static cn.hutool.core.util.RandomUtil.randomEle;
44 import static com.iailab.framework.common.util.collection.SetUtils.asSet;
45 import static com.iailab.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime;
46 import static com.iailab.framework.common.util.date.LocalDateTimeUtils.buildTime;
47 import static com.iailab.framework.common.util.object.ObjectUtils.cloneIgnoreId;
48 import static com.iailab.framework.test.core.util.AssertUtils.assertPojoEquals;
49 import static com.iailab.framework.test.core.util.AssertUtils.assertServiceException;
50 import static com.iailab.framework.test.core.util.RandomUtils.*;
51 import static com.iailab.module.system.enums.ErrorCodeConstants.*;
52 import static java.util.Collections.singleton;
53 import static java.util.Collections.singletonList;
54 import static org.assertj.core.util.Lists.newArrayList;
55 import static org.junit.jupiter.api.Assertions.*;
56 import static org.mockito.ArgumentMatchers.*;
57 import static org.mockito.Mockito.*;
58
59 @Import(AdminUserServiceImpl.class)
60 public class AdminUserServiceImplTest extends BaseDbUnitTest {
61
62     @Resource
63     private AdminUserServiceImpl userService;
64
65     @Resource
66     private AdminUserMapper userMapper;
67     @Resource
68     private UserPostMapper userPostMapper;
69
70     @MockBean
71     private DeptService deptService;
72     @MockBean
73     private PostService postService;
74     @MockBean
75     private PermissionService permissionService;
76     @MockBean
77     private PasswordEncoder passwordEncoder;
78     @MockBean
79     private TenantService tenantService;
80     @MockBean
81     private FileApi fileApi;
82
83     @Test
84     public void testCreatUser_success() {
85         // 准备参数
86         UserSaveReqVO reqVO = randomPojo(UserSaveReqVO.class, o -> {
87             o.setSex(RandomUtil.randomEle(SexEnum.values()).getSex());
88             o.setMobile(randomString());
89             o.setPostIds(asSet(1L, 2L));
90         }).setId(null); // 避免 id 被赋值
91         // mock 账户额度充足
92         TenantDO tenant = randomPojo(TenantDO.class, o -> o.setAccountCount(1));
93         doNothing().when(tenantService).handleTenantInfo(argThat(handler -> {
94             handler.handle(tenant);
95             return true;
96         }));
97         // mock deptService 的方法
98         DeptDO dept = randomPojo(DeptDO.class, o -> {
99             o.setId(reqVO.getDeptId());
100             o.setStatus(CommonStatusEnum.ENABLE.getStatus());
101         });
102         when(deptService.getDept(eq(dept.getId()))).thenReturn(dept);
103         // mock postService 的方法
104         List<PostDO> posts = CollectionUtils.convertList(reqVO.getPostIds(), postId ->
105                 randomPojo(PostDO.class, o -> {
106                     o.setId(postId);
107                     o.setStatus(CommonStatusEnum.ENABLE.getStatus());
108                 }));
109         when(postService.getPostList(eq(reqVO.getPostIds()), isNull())).thenReturn(posts);
110         // mock passwordEncoder 的方法
111         when(passwordEncoder.encode(eq(reqVO.getPassword()))).thenReturn("iailabyuanma");
112
113         // 调用
114         Long userId = userService.createUser(reqVO);
115         // 断言
116         AdminUserDO user = userMapper.selectById(userId);
117         assertPojoEquals(reqVO, user, "password", "id");
118         assertEquals("iailabyuanma", user.getPassword());
119         assertEquals(CommonStatusEnum.ENABLE.getStatus(), user.getStatus());
120         // 断言关联岗位
121         List<UserPostDO> userPosts = userPostMapper.selectListByUserId(user.getId());
122         assertEquals(1L, userPosts.get(0).getPostId());
123         assertEquals(2L, userPosts.get(1).getPostId());
124     }
125
126     @Test
127     public void testCreatUser_max() {
128         // 准备参数
129         UserSaveReqVO reqVO = randomPojo(UserSaveReqVO.class);
130         // mock 账户额度不足
131         TenantDO tenant = randomPojo(TenantDO.class, o -> o.setAccountCount(-1));
132         doNothing().when(tenantService).handleTenantInfo(argThat(handler -> {
133             handler.handle(tenant);
134             return true;
135         }));
136
137         // 调用,并断言异常
138         assertServiceException(() -> userService.createUser(reqVO), USER_COUNT_MAX, -1);
139     }
140
141     @Test
142     public void testUpdateUser_success() {
143         // mock 数据
144         AdminUserDO dbUser = randomAdminUserDO(o -> o.setPostIds(asSet(1L, 2L)));
145         userMapper.insert(dbUser);
146         userPostMapper.insert(new UserPostDO().setUserId(dbUser.getId()).setPostId(1L));
147         userPostMapper.insert(new UserPostDO().setUserId(dbUser.getId()).setPostId(2L));
148         // 准备参数
149         UserSaveReqVO reqVO = randomPojo(UserSaveReqVO.class, o -> {
150             o.setId(dbUser.getId());
151             o.setSex(RandomUtil.randomEle(SexEnum.values()).getSex());
152             o.setMobile(randomString());
153             o.setPostIds(asSet(2L, 3L));
154         });
155         // mock deptService 的方法
156         DeptDO dept = randomPojo(DeptDO.class, o -> {
157             o.setId(reqVO.getDeptId());
158             o.setStatus(CommonStatusEnum.ENABLE.getStatus());
159         });
160         when(deptService.getDept(eq(dept.getId()))).thenReturn(dept);
161         // mock postService 的方法
162         List<PostDO> posts = CollectionUtils.convertList(reqVO.getPostIds(), postId ->
163                 randomPojo(PostDO.class, o -> {
164                     o.setId(postId);
165                     o.setStatus(CommonStatusEnum.ENABLE.getStatus());
166                 }));
167         when(postService.getPostList(eq(reqVO.getPostIds()), isNull())).thenReturn(posts);
168
169         // 调用
170         userService.updateUser(reqVO);
171         // 断言
172         AdminUserDO user = userMapper.selectById(reqVO.getId());
173         assertPojoEquals(reqVO, user, "password");
174         // 断言关联岗位
175         List<UserPostDO> userPosts = userPostMapper.selectListByUserId(user.getId());
176         assertEquals(2L, userPosts.get(0).getPostId());
177         assertEquals(3L, userPosts.get(1).getPostId());
178     }
179
180     @Test
181     public void testUpdateUserLogin() {
182         // mock 数据
183         AdminUserDO user = randomAdminUserDO(o -> o.setLoginDate(null));
184         userMapper.insert(user);
185         // 准备参数
186         Long id = user.getId();
187         String loginIp = randomString();
188
189         // 调用
190         userService.updateUserLogin(id, loginIp);
191         // 断言
192         AdminUserDO dbUser = userMapper.selectById(id);
193         assertEquals(loginIp, dbUser.getLoginIp());
194         assertNotNull(dbUser.getLoginDate());
195     }
196
197     @Test
198     public void testUpdateUserProfile_success() {
199         // mock 数据
200         AdminUserDO dbUser = randomAdminUserDO();
201         userMapper.insert(dbUser);
202         // 准备参数
203         Long userId = dbUser.getId();
204         UserProfileUpdateReqVO reqVO = randomPojo(UserProfileUpdateReqVO.class, o -> {
205             o.setMobile(randomString());
206             o.setSex(RandomUtil.randomEle(SexEnum.values()).getSex());
207         });
208
209         // 调用
210         userService.updateUserProfile(userId, reqVO);
211         // 断言
212         AdminUserDO user = userMapper.selectById(userId);
213         assertPojoEquals(reqVO, user);
214     }
215
216     @Test
217     public void testUpdateUserPassword_success() {
218         // mock 数据
219         AdminUserDO dbUser = randomAdminUserDO(o -> o.setPassword("encode:tudou"));
220         userMapper.insert(dbUser);
221         // 准备参数
222         Long userId = dbUser.getId();
223         UserProfileUpdatePasswordReqVO reqVO = randomPojo(UserProfileUpdatePasswordReqVO.class, o -> {
224             o.setOldPassword("tudou");
225             o.setNewPassword("yuanma");
226         });
227         // mock 方法
228         when(passwordEncoder.encode(anyString())).then(
229                 (Answer<String>) invocationOnMock -> "encode:" + invocationOnMock.getArgument(0));
230         when(passwordEncoder.matches(eq(reqVO.getOldPassword()), eq(dbUser.getPassword()))).thenReturn(true);
231
232         // 调用
233         userService.updateUserPassword(userId, reqVO);
234         // 断言
235         AdminUserDO user = userMapper.selectById(userId);
236         assertEquals("encode:yuanma", user.getPassword());
237     }
238
239     @Test
240     public void testUpdateUserAvatar_success() throws Exception {
241         // mock 数据
242         AdminUserDO dbUser = randomAdminUserDO();
243         userMapper.insert(dbUser);
244         // 准备参数
245         Long userId = dbUser.getId();
246         byte[] avatarFileBytes = randomBytes(10);
247         ByteArrayInputStream avatarFile = new ByteArrayInputStream(avatarFileBytes);
248         // mock 方法
249         String avatar = randomString();
250         when(fileApi.createFile(eq( avatarFileBytes))).thenReturn(avatar);
251
252         // 调用
253         userService.updateUserAvatar(userId, avatarFile);
254         // 断言
255         AdminUserDO user = userMapper.selectById(userId);
256         assertEquals(avatar, user.getAvatar());
257     }
258
259     @Test
260     public void testUpdateUserPassword02_success() {
261         // mock 数据
262         AdminUserDO dbUser = randomAdminUserDO();
263         userMapper.insert(dbUser);
264         // 准备参数
265         Long userId = dbUser.getId();
266         String password = "iailab";
267         // mock 方法
268         when(passwordEncoder.encode(anyString())).then(
269                 (Answer<String>) invocationOnMock -> "encode:" + invocationOnMock.getArgument(0));
270
271         // 调用
272         userService.updateUserPassword(userId, password);
273         // 断言
274         AdminUserDO user = userMapper.selectById(userId);
275         assertEquals("encode:" + password, user.getPassword());
276     }
277
278     @Test
279     public void testUpdateUserStatus() {
280         // mock 数据
281         AdminUserDO dbUser = randomAdminUserDO();
282         userMapper.insert(dbUser);
283         // 准备参数
284         Long userId = dbUser.getId();
285         Integer status = randomCommonStatus();
286
287         // 调用
288         userService.updateUserStatus(userId, status);
289         // 断言
290         AdminUserDO user = userMapper.selectById(userId);
291         assertEquals(status, user.getStatus());
292     }
293
294     @Test
295     public void testDeleteUser_success(){
296         // mock 数据
297         AdminUserDO dbUser = randomAdminUserDO();
298         userMapper.insert(dbUser);
299         // 准备参数
300         Long userId = dbUser.getId();
301
302         // 调用数据
303         userService.deleteUser(userId);
304         // 校验结果
305         assertNull(userMapper.selectById(userId));
306         // 校验调用次数
307         verify(permissionService, times(1)).processUserDeleted(eq(userId));
308     }
309
310     @Test
311     public void testGetUserByUsername() {
312         // mock 数据
313         AdminUserDO dbUser = randomAdminUserDO();
314         userMapper.insert(dbUser);
315         // 准备参数
316         String username = dbUser.getUsername();
317
318         // 调用
319         AdminUserDO user = userService.getUserByUsername(username);
320         // 断言
321         assertPojoEquals(dbUser, user);
322     }
323
324     @Test
325     public void testGetUserByMobile() {
326         // mock 数据
327         AdminUserDO dbUser = randomAdminUserDO();
328         userMapper.insert(dbUser);
329         // 准备参数
330         String mobile = dbUser.getMobile();
331
332         // 调用
333         AdminUserDO user = userService.getUserByMobile(mobile);
334         // 断言
335         assertPojoEquals(dbUser, user);
336     }
337
338     @Test
339     public void testGetUserPage() {
340         // mock 数据
341         AdminUserDO dbUser = initGetUserPageData();
342         // 准备参数
343         UserPageReqVO reqVO = new UserPageReqVO();
344         reqVO.setUsername("tu");
345         reqVO.setMobile("1560");
346         reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
347         reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24));
348         reqVO.setDeptId(1L); // 其中,1L 是 2L 的父部门
349         // mock 方法
350         List<DeptDO> deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L)));
351         when(deptService.getChildDeptList(eq(reqVO.getDeptId()))).thenReturn(deptList);
352
353         // 调用
354         PageResult<AdminUserDO> pageResult = userService.getUserPage(reqVO);
355         // 断言
356         assertEquals(1, pageResult.getTotal());
357         assertEquals(1, pageResult.getList().size());
358         assertPojoEquals(dbUser, pageResult.getList().get(0));
359     }
360
361     /**
362      * 初始化 getUserPage 方法的测试数据
363      */
364     private AdminUserDO initGetUserPageData() {
365         // mock 数据
366         AdminUserDO dbUser = randomAdminUserDO(o -> { // 等会查询到
367             o.setUsername("tudou");
368             o.setMobile("15601691300");
369             o.setStatus(CommonStatusEnum.ENABLE.getStatus());
370             o.setCreateTime(buildTime(2020, 12, 12));
371             o.setDeptId(2L);
372         });
373         userMapper.insert(dbUser);
374         // 测试 username 不匹配
375         userMapper.insert(cloneIgnoreId(dbUser, o -> o.setUsername("dou")));
376         // 测试 mobile 不匹配
377         userMapper.insert(cloneIgnoreId(dbUser, o -> o.setMobile("18818260888")));
378         // 测试 status 不匹配
379         userMapper.insert(cloneIgnoreId(dbUser, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
380         // 测试 createTime 不匹配
381         userMapper.insert(cloneIgnoreId(dbUser, o -> o.setCreateTime(buildTime(2020, 11, 11))));
382         // 测试 dept 不匹配
383         userMapper.insert(cloneIgnoreId(dbUser, o -> o.setDeptId(0L)));
384         return dbUser;
385     }
386
387     @Test
388     public void testGetUser() {
389         // mock 数据
390         AdminUserDO dbUser = randomAdminUserDO();
391         userMapper.insert(dbUser);
392         // 准备参数
393         Long userId = dbUser.getId();
394
395         // 调用
396         AdminUserDO user = userService.getUser(userId);
397         // 断言
398         assertPojoEquals(dbUser, user);
399     }
400
401     @Test
402     public void testGetUserListByDeptIds() {
403         // mock 数据
404         AdminUserDO dbUser = randomAdminUserDO(o -> o.setDeptId(1L));
405         userMapper.insert(dbUser);
406         // 测试 deptId 不匹配
407         userMapper.insert(cloneIgnoreId(dbUser, o -> o.setDeptId(2L)));
408         // 准备参数
409         Collection<Long> deptIds = singleton(1L);
410
411         // 调用
412         List<AdminUserDO> list = userService.getUserListByDeptIds(deptIds);
413         // 断言
414         assertEquals(1, list.size());
415         assertEquals(dbUser, list.get(0));
416     }
417
418     /**
419      * 情况一,校验不通过,导致插入失败
420      */
421     @Test
422     public void testImportUserList_01() {
423         // 准备参数
424         UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
425         });
426         // mock 方法,模拟失败
427         doThrow(new ServiceException(DEPT_NOT_FOUND)).when(deptService).validateDeptList(any());
428
429         // 调用
430         UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true);
431         // 断言
432         assertEquals(0, respVO.getCreateUsernames().size());
433         assertEquals(0, respVO.getUpdateUsernames().size());
434         assertEquals(1, respVO.getFailureUsernames().size());
435         assertEquals(DEPT_NOT_FOUND.getMsg(), respVO.getFailureUsernames().get(importUser.getUsername()));
436     }
437
438     /**
439      * 情况二,不存在,进行插入
440      */
441     @Test
442     public void testImportUserList_02() {
443         // 准备参数
444         UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
445             o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
446             o.setSex(randomEle(SexEnum.values()).getSex()); // 保证 sex 的范围
447         });
448         // mock deptService 的方法
449         DeptDO dept = randomPojo(DeptDO.class, o -> {
450             o.setId(importUser.getDeptId());
451             o.setStatus(CommonStatusEnum.ENABLE.getStatus());
452         });
453         when(deptService.getDept(eq(dept.getId()))).thenReturn(dept);
454         // mock passwordEncoder 的方法
455         when(passwordEncoder.encode(eq("iailabyuanma"))).thenReturn("java");
456
457         // 调用
458         UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true);
459         // 断言
460         assertEquals(1, respVO.getCreateUsernames().size());
461         AdminUserDO user = userMapper.selectByUsername(respVO.getCreateUsernames().get(0));
462         assertPojoEquals(importUser, user);
463         assertEquals("java", user.getPassword());
464         assertEquals(0, respVO.getUpdateUsernames().size());
465         assertEquals(0, respVO.getFailureUsernames().size());
466     }
467
468     /**
469      * 情况三,存在,但是不强制更新
470      */
471     @Test
472     public void testImportUserList_03() {
473         // mock 数据
474         AdminUserDO dbUser = randomAdminUserDO();
475         userMapper.insert(dbUser);
476         // 准备参数
477         UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
478             o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
479             o.setSex(randomEle(SexEnum.values()).getSex()); // 保证 sex 的范围
480             o.setUsername(dbUser.getUsername());
481         });
482         // mock deptService 的方法
483         DeptDO dept = randomPojo(DeptDO.class, o -> {
484             o.setId(importUser.getDeptId());
485             o.setStatus(CommonStatusEnum.ENABLE.getStatus());
486         });
487         when(deptService.getDept(eq(dept.getId()))).thenReturn(dept);
488
489         // 调用
490         UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), false);
491         // 断言
492         assertEquals(0, respVO.getCreateUsernames().size());
493         assertEquals(0, respVO.getUpdateUsernames().size());
494         assertEquals(1, respVO.getFailureUsernames().size());
495         assertEquals(USER_USERNAME_EXISTS.getMsg(), respVO.getFailureUsernames().get(importUser.getUsername()));
496     }
497
498     /**
499      * 情况四,存在,强制更新
500      */
501     @Test
502     public void testImportUserList_04() {
503         // mock 数据
504         AdminUserDO dbUser = randomAdminUserDO();
505         userMapper.insert(dbUser);
506         // 准备参数
507         UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
508             o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
509             o.setSex(randomEle(SexEnum.values()).getSex()); // 保证 sex 的范围
510             o.setUsername(dbUser.getUsername());
511         });
512         // mock deptService 的方法
513         DeptDO dept = randomPojo(DeptDO.class, o -> {
514             o.setId(importUser.getDeptId());
515             o.setStatus(CommonStatusEnum.ENABLE.getStatus());
516         });
517         when(deptService.getDept(eq(dept.getId()))).thenReturn(dept);
518
519         // 调用
520         UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true);
521         // 断言
522         assertEquals(0, respVO.getCreateUsernames().size());
523         assertEquals(1, respVO.getUpdateUsernames().size());
524         AdminUserDO user = userMapper.selectByUsername(respVO.getUpdateUsernames().get(0));
525         assertPojoEquals(importUser, user);
526         assertEquals(0, respVO.getFailureUsernames().size());
527     }
528
529     @Test
530     public void testValidateUserExists_notExists() {
531         assertServiceException(() -> userService.validateUserExists(randomLongId()), USER_NOT_EXISTS);
532     }
533
534     @Test
535     public void testValidateUsernameUnique_usernameExistsForCreate() {
536         // 准备参数
537         String username = randomString();
538         // mock 数据
539         userMapper.insert(randomAdminUserDO(o -> o.setUsername(username)));
540
541         // 调用,校验异常
542         assertServiceException(() -> userService.validateUsernameUnique(null, username),
543                 USER_USERNAME_EXISTS);
544     }
545
546     @Test
547     public void testValidateUsernameUnique_usernameExistsForUpdate() {
548         // 准备参数
549         Long id = randomLongId();
550         String username = randomString();
551         // mock 数据
552         userMapper.insert(randomAdminUserDO(o -> o.setUsername(username)));
553
554         // 调用,校验异常
555         assertServiceException(() -> userService.validateUsernameUnique(id, username),
556                 USER_USERNAME_EXISTS);
557     }
558
559     @Test
560     public void testValidateEmailUnique_emailExistsForCreate() {
561         // 准备参数
562         String email = randomString();
563         // mock 数据
564         userMapper.insert(randomAdminUserDO(o -> o.setEmail(email)));
565
566         // 调用,校验异常
567         assertServiceException(() -> userService.validateEmailUnique(null, email),
568                 USER_EMAIL_EXISTS);
569     }
570
571     @Test
572     public void testValidateEmailUnique_emailExistsForUpdate() {
573         // 准备参数
574         Long id = randomLongId();
575         String email = randomString();
576         // mock 数据
577         userMapper.insert(randomAdminUserDO(o -> o.setEmail(email)));
578
579         // 调用,校验异常
580         assertServiceException(() -> userService.validateEmailUnique(id, email),
581                 USER_EMAIL_EXISTS);
582     }
583
584     @Test
585     public void testValidateMobileUnique_mobileExistsForCreate() {
586         // 准备参数
587         String mobile = randomString();
588         // mock 数据
589         userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile)));
590
591         // 调用,校验异常
592         assertServiceException(() -> userService.validateMobileUnique(null, mobile),
593                 USER_MOBILE_EXISTS);
594     }
595
596     @Test
597     public void testValidateMobileUnique_mobileExistsForUpdate() {
598         // 准备参数
599         Long id = randomLongId();
600         String mobile = randomString();
601         // mock 数据
602         userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile)));
603
604         // 调用,校验异常
605         assertServiceException(() -> userService.validateMobileUnique(id, mobile),
606                 USER_MOBILE_EXISTS);
607     }
608
609     @Test
610     public void testValidateOldPassword_notExists() {
611         assertServiceException(() -> userService.validateOldPassword(randomLongId(), randomString()),
612                 USER_NOT_EXISTS);
613     }
614
615     @Test
616     public void testValidateOldPassword_passwordFailed() {
617         // mock 数据
618         AdminUserDO user = randomAdminUserDO();
619         userMapper.insert(user);
620         // 准备参数
621         Long id = user.getId();
622         String oldPassword = user.getPassword();
623
624         // 调用,校验异常
625         assertServiceException(() -> userService.validateOldPassword(id, oldPassword),
626                 USER_PASSWORD_FAILED);
627         // 校验调用
628         verify(passwordEncoder, times(1)).matches(eq(oldPassword), eq(user.getPassword()));
629     }
630
631     @Test
632     public void testUserListByPostIds() {
633         // 准备参数
634         Collection<Long> postIds = asSet(10L, 20L);
635         // mock user1 数据
636         AdminUserDO user1 = randomAdminUserDO(o -> o.setPostIds(asSet(10L, 30L)));
637         userMapper.insert(user1);
638         userPostMapper.insert(new UserPostDO().setUserId(user1.getId()).setPostId(10L));
639         userPostMapper.insert(new UserPostDO().setUserId(user1.getId()).setPostId(30L));
640         // mock user2 数据
641         AdminUserDO user2 = randomAdminUserDO(o -> o.setPostIds(singleton(100L)));
642         userMapper.insert(user2);
643         userPostMapper.insert(new UserPostDO().setUserId(user2.getId()).setPostId(100L));
644
645         // 调用
646         List<AdminUserDO> result = userService.getUserListByPostIds(postIds);
647         // 断言
648         assertEquals(1, result.size());
649         assertEquals(user1, result.get(0));
650     }
651
652     @Test
653     public void testGetUserList() {
654         // mock 数据
655         AdminUserDO user = randomAdminUserDO();
656         userMapper.insert(user);
657         // 测试 id 不匹配
658         userMapper.insert(randomAdminUserDO());
659         // 准备参数
660         Collection<Long> ids = singleton(user.getId());
661
662         // 调用
663         List<AdminUserDO> result = userService.getUserList(ids);
664         // 断言
665         assertEquals(1, result.size());
666         assertEquals(user, result.get(0));
667     }
668
669     @Test
670     public void testGetUserMap() {
671         // mock 数据
672         AdminUserDO user = randomAdminUserDO();
673         userMapper.insert(user);
674         // 测试 id 不匹配
675         userMapper.insert(randomAdminUserDO());
676         // 准备参数
677         Collection<Long> ids = singleton(user.getId());
678
679         // 调用
680         Map<Long, AdminUserDO> result = userService.getUserMap(ids);
681         // 断言
682         assertEquals(1, result.size());
683         assertEquals(user, result.get(user.getId()));
684     }
685
686     @Test
687     public void testGetUserListByNickname() {
688         // mock 数据
689         AdminUserDO user = randomAdminUserDO(o -> o.setNickname("芋头"));
690         userMapper.insert(user);
691         // 测试 nickname 不匹配
692         userMapper.insert(randomAdminUserDO(o -> o.setNickname("源码")));
693         // 准备参数
694         String nickname = "芋";
695
696         // 调用
697         List<AdminUserDO> result = userService.getUserListByNickname(nickname);
698         // 断言
699         assertEquals(1, result.size());
700         assertEquals(user, result.get(0));
701     }
702
703     @Test
704     public void testGetUserListByStatus() {
705         // mock 数据
706         AdminUserDO user = randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()));
707         userMapper.insert(user);
708         // 测试 status 不匹配
709         userMapper.insert(randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())));
710         // 准备参数
711         Integer status = CommonStatusEnum.DISABLE.getStatus();
712
713         // 调用
714         List<AdminUserDO> result = userService.getUserListByStatus(status);
715         // 断言
716         assertEquals(1, result.size());
717         assertEquals(user, result.get(0));
718     }
719
720     @Test
721     public void testValidateUserList_success() {
722         // mock 数据
723         AdminUserDO userDO = randomAdminUserDO().setStatus(CommonStatusEnum.ENABLE.getStatus());
724         userMapper.insert(userDO);
725         // 准备参数
726         List<Long> ids = singletonList(userDO.getId());
727
728         // 调用,无需断言
729         userService.validateUserList(ids);
730     }
731
732     @Test
733     public void testValidateUserList_notFound() {
734         // 准备参数
735         List<Long> ids = singletonList(randomLongId());
736
737         // 调用, 并断言异常
738         assertServiceException(() -> userService.validateUserList(ids), USER_NOT_EXISTS);
739     }
740
741     @Test
742     public void testValidateUserList_notEnable() {
743         // mock 数据
744         AdminUserDO userDO = randomAdminUserDO().setStatus(CommonStatusEnum.DISABLE.getStatus());
745         userMapper.insert(userDO);
746         // 准备参数
747         List<Long> ids = singletonList(userDO.getId());
748
749         // 调用, 并断言异常
750         assertServiceException(() -> userService.validateUserList(ids), USER_IS_DISABLE,
751                 userDO.getNickname());
752     }
753
754     // ========== 随机对象 ==========
755
756     @SafeVarargs
757     private static AdminUserDO randomAdminUserDO(Consumer<AdminUserDO>... consumers) {
758         Consumer<AdminUserDO> consumer = (o) -> {
759             o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
760             o.setSex(randomEle(SexEnum.values()).getSex()); // 保证 sex 的范围
761         };
762         return randomPojo(AdminUserDO.class, ArrayUtils.append(consumer, consumers));
763     }
764
765 }