完善 AdminUserServiceImpl 单元测试

This commit is contained in:
YunaiV 2023-02-03 22:09:55 +08:00
parent 6474fba923
commit 5619441f61
13 changed files with 367 additions and 150 deletions

View File

@ -0,0 +1,43 @@
package cn.iocoder.yudao.framework.datapermission.core.util;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.framework.datapermission.core.aop.DataPermissionContextHolder;
import lombok.SneakyThrows;
/**
* 数据权限 Util
*
* @author 芋道源码
*/
public class DataPermissionUtils {
private static DataPermission DATA_PERMISSION_DISABLE;
@DataPermission(enable = false)
@SneakyThrows
private static DataPermission getDisableDataPermissionDisable() {
if (DATA_PERMISSION_DISABLE == null) {
DATA_PERMISSION_DISABLE = DataPermissionUtils.class
.getDeclaredMethod("getDisableDataPermissionDisable")
.getAnnotation(DataPermission.class);
}
return DATA_PERMISSION_DISABLE;
}
/**
* 忽略数据权限执行对应的逻辑
*
* @param runnable 逻辑
*/
public static void executeIgnore(Runnable runnable) {
DataPermission dataPermission = getDisableDataPermissionDisable();
DataPermissionContextHolder.add(dataPermission);
try {
// 执行 runnable
runnable.run();
} finally {
DataPermissionContextHolder.remove();
}
}
}

View File

@ -0,0 +1,16 @@
package cn.iocoder.yudao.framework.datapermission.core.utils;
import cn.iocoder.yudao.framework.datapermission.core.aop.DataPermissionContextHolder;
import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class DataPermissionUtilsTest {
@Test
public void testExecuteIgnore() {
DataPermissionUtils.executeIgnore(() -> assertFalse(DataPermissionContextHolder.get().enable()));
}
}

View File

@ -220,7 +220,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {
} else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.POST.getType())) { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.POST.getType())) {
postApi.validPostList(options); postApi.validPostList(options);
} else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER.getType())) { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER.getType())) {
adminUserApi.validUsers(options); adminUserApi.validUserList(options);
} else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER_GROUP.getType())) { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER_GROUP.getType())) {
userGroupService.validUserGroups(options); userGroupService.validUserGroups(options);
} else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.SCRIPT.getType())) { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.SCRIPT.getType())) {
@ -288,7 +288,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {
} }
private Set<Long> calculateTaskCandidateUsersByDeptMember(BpmTaskAssignRuleDO rule) { private Set<Long> calculateTaskCandidateUsersByDeptMember(BpmTaskAssignRuleDO rule) {
List<AdminUserRespDTO> users = adminUserApi.getUsersByDeptIds(rule.getOptions()).getCheckedData(); List<AdminUserRespDTO> users = adminUserApi.getUserListByDeptIds(rule.getOptions()).getCheckedData();
return convertSet(users, AdminUserRespDTO::getId); return convertSet(users, AdminUserRespDTO::getId);
} }
@ -298,7 +298,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {
} }
private Set<Long> calculateTaskCandidateUsersByPost(BpmTaskAssignRuleDO rule) { private Set<Long> calculateTaskCandidateUsersByPost(BpmTaskAssignRuleDO rule) {
List<AdminUserRespDTO> users = adminUserApi.getUsersByPostIds(rule.getOptions()).getCheckedData(); List<AdminUserRespDTO> users = adminUserApi.getUserListByPostIds(rule.getOptions()).getCheckedData();
return convertSet(users, AdminUserRespDTO::getId); return convertSet(users, AdminUserRespDTO::getId);
} }

View File

@ -87,7 +87,7 @@ public class BpmTaskAssignRuleServiceImplTest extends BaseDbUnitTest {
// mock 方法 // mock 方法
List<AdminUserRespDTO> users = CollectionUtils.convertList(asSet(11L, 22L), List<AdminUserRespDTO> users = CollectionUtils.convertList(asSet(11L, 22L),
id -> new AdminUserRespDTO().setId(id)); id -> new AdminUserRespDTO().setId(id));
when(adminUserApi.getUsersByDeptIds(eq(rule.getOptions()))).thenReturn(success(users)); when(adminUserApi.getUserListByDeptIds(eq(rule.getOptions()))).thenReturn(success(users));
mockGetUserMap(asSet(11L, 22L)); mockGetUserMap(asSet(11L, 22L));
// 调用 // 调用
@ -121,7 +121,7 @@ public class BpmTaskAssignRuleServiceImplTest extends BaseDbUnitTest {
// mock 方法 // mock 方法
List<AdminUserRespDTO> users = CollectionUtils.convertList(asSet(11L, 22L), List<AdminUserRespDTO> users = CollectionUtils.convertList(asSet(11L, 22L),
id -> new AdminUserRespDTO().setId(id)); id -> new AdminUserRespDTO().setId(id));
when(adminUserApi.getUsersByPostIds(eq(rule.getOptions()))).thenReturn(success(users)); when(adminUserApi.getUserListByPostIds(eq(rule.getOptions()))).thenReturn(success(users));
mockGetUserMap(asSet(11L, 22L)); mockGetUserMap(asSet(11L, 22L));
// 调用 // 调用

View File

@ -30,17 +30,17 @@ public interface AdminUserApi {
@GetMapping(PREFIX + "/list") @GetMapping(PREFIX + "/list")
@ApiOperation("通过用户 ID 查询用户们") @ApiOperation("通过用户 ID 查询用户们")
@ApiImplicitParam(name = "ids", value = "部门编号数组", example = "1,2", required = true, allowMultiple = true) @ApiImplicitParam(name = "ids", value = "部门编号数组", example = "1,2", required = true, allowMultiple = true)
CommonResult<List<AdminUserRespDTO>> getUsers(@RequestParam("ids") Collection<Long> ids); CommonResult<List<AdminUserRespDTO>> getUserList(@RequestParam("ids") Collection<Long> ids);
@GetMapping(PREFIX + "/list-by-dept-id") @GetMapping(PREFIX + "/list-by-dept-id")
@ApiOperation("获得指定部门的用户数组") @ApiOperation("获得指定部门的用户数组")
@ApiImplicitParam(name = "deptIds", value = "部门编号数组", example = "1,2", required = true, allowMultiple = true) @ApiImplicitParam(name = "deptIds", value = "部门编号数组", example = "1,2", required = true, allowMultiple = true)
CommonResult<List<AdminUserRespDTO>> getUsersByDeptIds(@RequestParam("deptIds") Collection<Long> deptIds); CommonResult<List<AdminUserRespDTO>> getUserListByDeptIds(@RequestParam("deptIds") Collection<Long> deptIds);
@GetMapping(PREFIX + "/list-by-post-id") @GetMapping(PREFIX + "/list-by-post-id")
@ApiOperation("获得指定岗位的用户数组") @ApiOperation("获得指定岗位的用户数组")
@ApiImplicitParam(name = "postIds", value = "岗位编号数组", example = "2,3", required = true, allowMultiple = true) @ApiImplicitParam(name = "postIds", value = "岗位编号数组", example = "2,3", required = true, allowMultiple = true)
CommonResult<List<AdminUserRespDTO>> getUsersByPostIds(@RequestParam("postIds") Collection<Long> postIds); CommonResult<List<AdminUserRespDTO>> getUserListByPostIds(@RequestParam("postIds") Collection<Long> postIds);
/** /**
* 获得用户 Map * 获得用户 Map
@ -49,12 +49,12 @@ public interface AdminUserApi {
* @return 用户 Map * @return 用户 Map
*/ */
default Map<Long, AdminUserRespDTO> getUserMap(Collection<Long> ids) { default Map<Long, AdminUserRespDTO> getUserMap(Collection<Long> ids) {
return CollectionUtils.convertMap(getUsers(ids).getCheckedData(), AdminUserRespDTO::getId); return CollectionUtils.convertMap(getUserList(ids).getCheckedData(), AdminUserRespDTO::getId);
} }
@GetMapping(PREFIX + "/valid") @GetMapping(PREFIX + "/valid")
@ApiOperation("校验用户们是否有效") @ApiOperation("校验用户们是否有效")
@ApiImplicitParam(name = "ids", value = "用户编号数组", example = "3,5", required = true) @ApiImplicitParam(name = "ids", value = "用户编号数组", example = "3,5", required = true)
CommonResult<Boolean> validUsers(@RequestParam("ids") Set<Long> ids); CommonResult<Boolean> validUserList(@RequestParam("ids") Set<Long> ids);
} }

View File

@ -33,26 +33,26 @@ public class AdminUserApiImpl implements AdminUserApi {
} }
@Override @Override
public CommonResult<List<AdminUserRespDTO>> getUsers(Collection<Long> ids) { public CommonResult<List<AdminUserRespDTO>> getUserList(Collection<Long> ids) {
List<AdminUserDO> users = userService.getUsers(ids); List<AdminUserDO> users = userService.getUserList(ids);
return success(UserConvert.INSTANCE.convertList4(users)); return success(UserConvert.INSTANCE.convertList4(users));
} }
@Override @Override
public CommonResult<List<AdminUserRespDTO>> getUsersByDeptIds(Collection<Long> deptIds) { public CommonResult<List<AdminUserRespDTO>> getUserListByDeptIds(Collection<Long> deptIds) {
List<AdminUserDO> users = userService.getUsersByDeptIds(deptIds); List<AdminUserDO> users = userService.getUserListByDeptIds(deptIds);
return success(UserConvert.INSTANCE.convertList4(users)); return success(UserConvert.INSTANCE.convertList4(users));
} }
@Override @Override
public CommonResult<List<AdminUserRespDTO>> getUsersByPostIds(Collection<Long> postIds) { public CommonResult<List<AdminUserRespDTO>> getUserListByPostIds(Collection<Long> postIds) {
List<AdminUserDO> users = userService.getUsersByPostIds(postIds); List<AdminUserDO> users = userService.getUserListByPostIds(postIds);
return success(UserConvert.INSTANCE.convertList4(users)); return success(UserConvert.INSTANCE.convertList4(users));
} }
@Override @Override
public CommonResult<Boolean> validUsers(Set<Long> ids) { public CommonResult<Boolean> validUserList(Set<Long> ids) {
userService.validUsers(ids); userService.validateUserList(ids);
return success(true); return success(true);
} }

View File

@ -111,9 +111,9 @@ public class UserController {
@GetMapping("/list-all-simple") @GetMapping("/list-all-simple")
@ApiOperation(value = "获取用户精简信息列表", notes = "只包含被开启的用户,主要用于前端的下拉选项") @ApiOperation(value = "获取用户精简信息列表", notes = "只包含被开启的用户,主要用于前端的下拉选项")
public CommonResult<List<UserSimpleRespVO>> getSimpleUsers() { public CommonResult<List<UserSimpleRespVO>> getSimpleUserList() {
// 获用户列表只要开启状态的 // 获用户列表只要开启状态的
List<AdminUserDO> list = userService.getUsersByStatus(CommonStatusEnum.ENABLE.getStatus()); List<AdminUserDO> list = userService.getUserListByStatus(CommonStatusEnum.ENABLE.getStatus());
// 排序后返回给前端 // 排序后返回给前端
return success(UserConvert.INSTANCE.convertList04(list)); return success(UserConvert.INSTANCE.convertList04(list));
} }
@ -122,7 +122,7 @@ public class UserController {
@ApiOperation("获得用户详情") @ApiOperation("获得用户详情")
@ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class) @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
@PreAuthorize("@ss.hasPermission('system:user:query')") @PreAuthorize("@ss.hasPermission('system:user:query')")
public CommonResult<UserRespVO> getInfo(@RequestParam("id") Long id) { public CommonResult<UserRespVO> getUser(@RequestParam("id") Long id) {
return success(UserConvert.INSTANCE.convert(userService.getUser(id))); return success(UserConvert.INSTANCE.convert(userService.getUser(id)));
} }
@ -130,10 +130,10 @@ public class UserController {
@ApiOperation("导出用户") @ApiOperation("导出用户")
@PreAuthorize("@ss.hasPermission('system:user:export')") @PreAuthorize("@ss.hasPermission('system:user:export')")
@OperateLog(type = EXPORT) @OperateLog(type = EXPORT)
public void exportUsers(@Validated UserExportReqVO reqVO, public void exportUserList(@Validated UserExportReqVO reqVO,
HttpServletResponse response) throws IOException { HttpServletResponse response) throws IOException {
// 获得用户列表 // 获得用户列表
List<AdminUserDO> users = userService.getUsers(reqVO); List<AdminUserDO> users = userService.getUserList(reqVO);
// 获得拼接需要的数据 // 获得拼接需要的数据
Collection<Long> deptIds = convertList(users, AdminUserDO::getDeptId); Collection<Long> deptIds = convertList(users, AdminUserDO::getDeptId);
@ -183,7 +183,7 @@ public class UserController {
public CommonResult<UserImportRespVO> importExcel(@RequestParam("file") MultipartFile file, public CommonResult<UserImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
@RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception { @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
List<UserImportExcelVO> list = ExcelUtils.read(file, UserImportExcelVO.class); List<UserImportExcelVO> list = ExcelUtils.read(file, UserImportExcelVO.class);
return success(userService.importUsers(list, updateSupport)); return success(userService.importUserList(list, updateSupport));
} }
} }

View File

@ -6,7 +6,6 @@ import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserExportReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserPageReqVO; import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import java.util.Collection; import java.util.Collection;
@ -16,15 +15,15 @@ import java.util.List;
public interface AdminUserMapper extends BaseMapperX<AdminUserDO> { public interface AdminUserMapper extends BaseMapperX<AdminUserDO> {
default AdminUserDO selectByUsername(String username) { default AdminUserDO selectByUsername(String username) {
return selectOne(new LambdaQueryWrapper<AdminUserDO>().eq(AdminUserDO::getUsername, username)); return selectOne(AdminUserDO::getUsername, username);
} }
default AdminUserDO selectByEmail(String email) { default AdminUserDO selectByEmail(String email) {
return selectOne(new LambdaQueryWrapper<AdminUserDO>().eq(AdminUserDO::getEmail, email)); return selectOne(AdminUserDO::getEmail, email);
} }
default AdminUserDO selectByMobile(String mobile) { default AdminUserDO selectByMobile(String mobile) {
return selectOne(new LambdaQueryWrapper<AdminUserDO>().eq(AdminUserDO::getMobile, mobile)); return selectOne(AdminUserDO::getMobile, mobile);
} }
default PageResult<AdminUserDO> selectPage(UserPageReqVO reqVO, Collection<Long> deptIds) { default PageResult<AdminUserDO> selectPage(UserPageReqVO reqVO, Collection<Long> deptIds) {
@ -50,10 +49,6 @@ public interface AdminUserMapper extends BaseMapperX<AdminUserDO> {
return selectList(new LambdaQueryWrapperX<AdminUserDO>().like(AdminUserDO::getNickname, nickname)); return selectList(new LambdaQueryWrapperX<AdminUserDO>().like(AdminUserDO::getNickname, nickname));
} }
default List<AdminUserDO> selectListByUsername(String username) {
return selectList(new LambdaQueryWrapperX<AdminUserDO>().like(AdminUserDO::getUsername, username));
}
default List<AdminUserDO> selectListByStatus(Integer status) { default List<AdminUserDO> selectListByStatus(Integer status) {
return selectList(AdminUserDO::getStatus, status); return selectList(AdminUserDO::getStatus, status);
} }

View File

@ -49,7 +49,7 @@ public class OperateLogServiceImpl implements OperateLogService {
// 处理基于用户昵称的查询 // 处理基于用户昵称的查询
Collection<Long> userIds = null; Collection<Long> userIds = null;
if (StrUtil.isNotEmpty(reqVO.getUserNickname())) { if (StrUtil.isNotEmpty(reqVO.getUserNickname())) {
userIds = convertSet(userService.getUsersByNickname(reqVO.getUserNickname()), AdminUserDO::getId); userIds = convertSet(userService.getUserListByNickname(reqVO.getUserNickname()), AdminUserDO::getId);
if (CollUtil.isEmpty(userIds)) { if (CollUtil.isEmpty(userIds)) {
return PageResult.empty(); return PageResult.empty();
} }
@ -63,7 +63,7 @@ public class OperateLogServiceImpl implements OperateLogService {
// 处理基于用户昵称的查询 // 处理基于用户昵称的查询
Collection<Long> userIds = null; Collection<Long> userIds = null;
if (StrUtil.isNotEmpty(reqVO.getUserNickname())) { if (StrUtil.isNotEmpty(reqVO.getUserNickname())) {
userIds = convertSet(userService.getUsersByNickname(reqVO.getUserNickname()), AdminUserDO::getId); userIds = convertSet(userService.getUserListByNickname(reqVO.getUserNickname()), AdminUserDO::getId);
if (CollUtil.isEmpty(userIds)) { if (CollUtil.isEmpty(userIds)) {
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -127,7 +127,7 @@ public interface AdminUserService {
* @param deptIds 部门数组 * @param deptIds 部门数组
* @return 用户数组 * @return 用户数组
*/ */
List<AdminUserDO> getUsersByDeptIds(Collection<Long> deptIds); List<AdminUserDO> getUserListByDeptIds(Collection<Long> deptIds);
/** /**
* 获得指定岗位的用户数组 * 获得指定岗位的用户数组
@ -135,7 +135,7 @@ public interface AdminUserService {
* @param postIds 岗位数组 * @param postIds 岗位数组
* @return 用户数组 * @return 用户数组
*/ */
List<AdminUserDO> getUsersByPostIds(Collection<Long> postIds); List<AdminUserDO> getUserListByPostIds(Collection<Long> postIds);
/** /**
* 获得用户列表 * 获得用户列表
@ -143,7 +143,7 @@ public interface AdminUserService {
* @param ids 用户编号数组 * @param ids 用户编号数组
* @return 用户列表 * @return 用户列表
*/ */
List<AdminUserDO> getUsers(Collection<Long> ids); List<AdminUserDO> getUserList(Collection<Long> ids);
/** /**
* 校验用户们是否有效如下情况视为无效 * 校验用户们是否有效如下情况视为无效
@ -152,7 +152,7 @@ public interface AdminUserService {
* *
* @param ids 用户编号数组 * @param ids 用户编号数组
*/ */
void validUsers(Set<Long> ids); void validateUserList(Collection<Long> ids);
/** /**
* 获得用户 Map * 获得用户 Map
@ -164,7 +164,7 @@ public interface AdminUserService {
if (CollUtil.isEmpty(ids)) { if (CollUtil.isEmpty(ids)) {
return new HashMap<>(); return new HashMap<>();
} }
return CollectionUtils.convertMap(getUsers(ids), AdminUserDO::getId); return CollectionUtils.convertMap(getUserList(ids), AdminUserDO::getId);
} }
/** /**
@ -173,7 +173,7 @@ public interface AdminUserService {
* @param reqVO 列表请求 * @param reqVO 列表请求
* @return 用户列表 * @return 用户列表
*/ */
List<AdminUserDO> getUsers(UserExportReqVO reqVO); List<AdminUserDO> getUserList(UserExportReqVO reqVO);
/** /**
* 获得用户列表基于昵称模糊匹配 * 获得用户列表基于昵称模糊匹配
@ -181,15 +181,7 @@ public interface AdminUserService {
* @param nickname 昵称 * @param nickname 昵称
* @return 用户列表 * @return 用户列表
*/ */
List<AdminUserDO> getUsersByNickname(String nickname); List<AdminUserDO> getUserListByNickname(String nickname);
/**
* 获得用户列表基于用户账号模糊匹配
*
* @param username 用户账号
* @return 用户列表
*/
List<AdminUserDO> getUsersByUsername(String username);
/** /**
* 批量导入用户 * 批量导入用户
@ -198,7 +190,7 @@ public interface AdminUserService {
* @param isUpdateSupport 是否支持更新 * @param isUpdateSupport 是否支持更新
* @return 导入结果 * @return 导入结果
*/ */
UserImportRespVO importUsers(List<UserImportExcelVO> importUsers, boolean isUpdateSupport); UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport);
/** /**
* 获得指定状态的用户们 * 获得指定状态的用户们
@ -206,7 +198,7 @@ public interface AdminUserService {
* @param status 状态 * @param status 状态
* @return 用户们 * @return 用户们
*/ */
List<AdminUserDO> getUsersByStatus(Integer status); List<AdminUserDO> getUserListByStatus(Integer status);
/** /**
* 判断密码是否匹配 * 判断密码是否匹配

View File

@ -8,7 +8,7 @@ import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.exception.ServiceException; import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission; import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils;
import cn.iocoder.yudao.module.infra.api.file.FileApi; import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO; import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO; import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO;
@ -43,6 +43,7 @@ import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
/** /**
* 后台用户 Service 实现类 * 后台用户 Service 实现类
*
* @author 芋道源码 * @author 芋道源码
*/ */
@Service("adminUserService") @Service("adminUserService")
@ -73,10 +74,6 @@ public class AdminUserServiceImpl implements AdminUserService {
@Resource @Resource
private FileApi fileApi; private FileApi fileApi;
@Resource
@Lazy // 循环依赖自己依赖自己避免报错
private AdminUserServiceImpl self;
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public Long createUser(UserCreateReqVO reqVO) { public Long createUser(UserCreateReqVO reqVO) {
@ -88,12 +85,12 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
}); });
// 校验正确性 // 校验正确性
self.checkCreateOrUpdate(null, reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), validateUserForCreateOrUpdate(null, reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(),
reqVO.getDeptId(), reqVO.getPostIds()); reqVO.getDeptId(), reqVO.getPostIds());
// 插入用户 // 插入用户
AdminUserDO user = UserConvert.INSTANCE.convert(reqVO); AdminUserDO user = UserConvert.INSTANCE.convert(reqVO);
user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启 user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
user.setPassword(passwordEncoder.encode(reqVO.getPassword())); // 加密密码 user.setPassword(encodePassword(reqVO.getPassword())); // 加密密码
userMapper.insert(user); userMapper.insert(user);
// 插入关联岗位 // 插入关联岗位
if (CollectionUtil.isNotEmpty(user.getPostIds())) { if (CollectionUtil.isNotEmpty(user.getPostIds())) {
@ -107,7 +104,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void updateUser(UserUpdateReqVO reqVO) { public void updateUser(UserUpdateReqVO reqVO) {
// 校验正确性 // 校验正确性
self.checkCreateOrUpdate(reqVO.getId(), reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), validateUserForCreateOrUpdate(reqVO.getId(), reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(),
reqVO.getDeptId(), reqVO.getPostIds()); reqVO.getDeptId(), reqVO.getPostIds());
// 更新用户 // 更新用户
AdminUserDO updateObj = UserConvert.INSTANCE.convert(reqVO); AdminUserDO updateObj = UserConvert.INSTANCE.convert(reqVO);
@ -141,9 +138,9 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
public void updateUserProfile(Long id, UserProfileUpdateReqVO reqVO) { public void updateUserProfile(Long id, UserProfileUpdateReqVO reqVO) {
// 校验正确性 // 校验正确性
checkUserExists(id); validateUserExists(id);
checkEmailUnique(id, reqVO.getEmail()); validateEmailUnique(id, reqVO.getEmail());
checkMobileUnique(id, reqVO.getMobile()); validateMobileUnique(id, reqVO.getMobile());
// 执行更新 // 执行更新
userMapper.updateById(UserConvert.INSTANCE.convert(reqVO).setId(id)); userMapper.updateById(UserConvert.INSTANCE.convert(reqVO).setId(id));
} }
@ -151,7 +148,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) { public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) {
// 校验旧密码密码 // 校验旧密码密码
checkOldPassword(id, reqVO.getOldPassword()); validateOldPassword(id, reqVO.getOldPassword());
// 执行更新 // 执行更新
AdminUserDO updateObj = new AdminUserDO().setId(id); AdminUserDO updateObj = new AdminUserDO().setId(id);
updateObj.setPassword(encodePassword(reqVO.getNewPassword())); // 加密密码 updateObj.setPassword(encodePassword(reqVO.getNewPassword())); // 加密密码
@ -160,7 +157,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
public String updateUserAvatar(Long id, InputStream avatarFile) throws Exception { public String updateUserAvatar(Long id, InputStream avatarFile) throws Exception {
checkUserExists(id); validateUserExists(id);
// 存储文件 // 存储文件
String avatar = fileApi.createFile(IoUtil.readBytes(avatarFile)); String avatar = fileApi.createFile(IoUtil.readBytes(avatarFile));
// 更新路径 // 更新路径
@ -174,7 +171,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
public void updateUserPassword(Long id, String password) { public void updateUserPassword(Long id, String password) {
// 校验用户存在 // 校验用户存在
checkUserExists(id); validateUserExists(id);
// 更新密码 // 更新密码
AdminUserDO updateObj = new AdminUserDO(); AdminUserDO updateObj = new AdminUserDO();
updateObj.setId(id); updateObj.setId(id);
@ -185,7 +182,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
public void updateUserStatus(Long id, Integer status) { public void updateUserStatus(Long id, Integer status) {
// 校验用户存在 // 校验用户存在
checkUserExists(id); validateUserExists(id);
// 更新状态 // 更新状态
AdminUserDO updateObj = new AdminUserDO(); AdminUserDO updateObj = new AdminUserDO();
updateObj.setId(id); updateObj.setId(id);
@ -197,7 +194,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void deleteUser(Long id) { public void deleteUser(Long id) {
// 校验用户存在 // 校验用户存在
checkUserExists(id); validateUserExists(id);
// 删除用户 // 删除用户
userMapper.deleteById(id); userMapper.deleteById(id);
// 删除用户关联数据 // 删除用户关联数据
@ -227,7 +224,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public List<AdminUserDO> getUsersByDeptIds(Collection<Long> deptIds) { public List<AdminUserDO> getUserListByDeptIds(Collection<Long> deptIds) {
if (CollUtil.isEmpty(deptIds)) { if (CollUtil.isEmpty(deptIds)) {
return Collections.emptyList(); return Collections.emptyList();
} }
@ -235,7 +232,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public List<AdminUserDO> getUsersByPostIds(Collection<Long> postIds) { public List<AdminUserDO> getUserListByPostIds(Collection<Long> postIds) {
if (CollUtil.isEmpty(postIds)) { if (CollUtil.isEmpty(postIds)) {
return Collections.emptyList(); return Collections.emptyList();
} }
@ -247,7 +244,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public List<AdminUserDO> getUsers(Collection<Long> ids) { public List<AdminUserDO> getUserList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) { if (CollUtil.isEmpty(ids)) {
return Collections.emptyList(); return Collections.emptyList();
} }
@ -255,7 +252,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public void validUsers(Set<Long> ids) { public void validateUserList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) { if (CollUtil.isEmpty(ids)) {
return; return;
} }
@ -275,20 +272,15 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public List<AdminUserDO> getUsers(UserExportReqVO reqVO) { public List<AdminUserDO> getUserList(UserExportReqVO reqVO) {
return userMapper.selectList(reqVO, getDeptCondition(reqVO.getDeptId())); return userMapper.selectList(reqVO, getDeptCondition(reqVO.getDeptId()));
} }
@Override @Override
public List<AdminUserDO> getUsersByNickname(String nickname) { public List<AdminUserDO> getUserListByNickname(String nickname) {
return userMapper.selectListByNickname(nickname); return userMapper.selectListByNickname(nickname);
} }
@Override
public List<AdminUserDO> getUsersByUsername(String username) {
return userMapper.selectListByUsername(username);
}
/** /**
* 获得部门条件查询指定部门的子部门编号们包括自身 * 获得部门条件查询指定部门的子部门编号们包括自身
* @param deptId 部门编号 * @param deptId 部门编号
@ -304,25 +296,27 @@ public class AdminUserServiceImpl implements AdminUserService {
return deptIds; return deptIds;
} }
@DataPermission(enable = false) // 关闭数据权限避免因为没有数据权限查询不到数据进而导致唯一校验不正确 private void validateUserForCreateOrUpdate(Long id, String username, String mobile, String email,
public void checkCreateOrUpdate(Long id, String username, String mobile, String email, Long deptId, Set<Long> postIds) {
Long deptId, Set<Long> postIds) { // 关闭数据权限避免因为没有数据权限查询不到数据进而导致唯一校验不正确
// 校验用户存在 DataPermissionUtils.executeIgnore(() -> {
checkUserExists(id); // 校验用户存在
// 校验用户名唯一 validateUserExists(id);
checkUsernameUnique(id, username); // 校验用户名唯一
// 校验手机号唯一 validateUsernameUnique(id, username);
checkMobileUnique(id, mobile); // 校验手机号唯一
// 校验邮箱唯一 validateMobileUnique(id, mobile);
checkEmailUnique(id, email); // 校验邮箱唯一
// 校验部门处于开启状态 validateEmailUnique(id, email);
deptService.validateDeptList(CollectionUtils.singleton(deptId)); // 校验部门处于开启状态
// 校验岗位处于开启状态 deptService.validateDeptList(CollectionUtils.singleton(deptId));
postService.validatePostList(postIds); // 校验岗位处于开启状态
postService.validatePostList(postIds);
});
} }
@VisibleForTesting @VisibleForTesting
public void checkUserExists(Long id) { void validateUserExists(Long id) {
if (id == null) { if (id == null) {
return; return;
} }
@ -333,7 +327,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@VisibleForTesting @VisibleForTesting
public void checkUsernameUnique(Long id, String username) { void validateUsernameUnique(Long id, String username) {
if (StrUtil.isBlank(username)) { if (StrUtil.isBlank(username)) {
return; return;
} }
@ -351,7 +345,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@VisibleForTesting @VisibleForTesting
public void checkEmailUnique(Long id, String email) { void validateEmailUnique(Long id, String email) {
if (StrUtil.isBlank(email)) { if (StrUtil.isBlank(email)) {
return; return;
} }
@ -369,7 +363,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@VisibleForTesting @VisibleForTesting
public void checkMobileUnique(Long id, String mobile) { void validateMobileUnique(Long id, String mobile) {
if (StrUtil.isBlank(mobile)) { if (StrUtil.isBlank(mobile)) {
return; return;
} }
@ -392,7 +386,7 @@ public class AdminUserServiceImpl implements AdminUserService {
* @param oldPassword 旧密码 * @param oldPassword 旧密码
*/ */
@VisibleForTesting @VisibleForTesting
public void checkOldPassword(Long id, String oldPassword) { void validateOldPassword(Long id, String oldPassword) {
AdminUserDO user = userMapper.selectById(id); AdminUserDO user = userMapper.selectById(id);
if (user == null) { if (user == null) {
throw exception(USER_NOT_EXISTS); throw exception(USER_NOT_EXISTS);
@ -404,7 +398,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
@Transactional(rollbackFor = Exception.class) // 添加事务异常则回滚所有导入 @Transactional(rollbackFor = Exception.class) // 添加事务异常则回滚所有导入
public UserImportRespVO importUsers(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) { public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) {
if (CollUtil.isEmpty(importUsers)) { if (CollUtil.isEmpty(importUsers)) {
throw exception(USER_IMPORT_LIST_IS_EMPTY); throw exception(USER_IMPORT_LIST_IS_EMPTY);
} }
@ -413,7 +407,7 @@ public class AdminUserServiceImpl implements AdminUserService {
importUsers.forEach(importUser -> { importUsers.forEach(importUser -> {
// 校验判断是否有不符合的原因 // 校验判断是否有不符合的原因
try { try {
checkCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail(), validateUserForCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail(),
importUser.getDeptId(), null); importUser.getDeptId(), null);
} catch (ServiceException ex) { } catch (ServiceException ex) {
respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage()); respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage());
@ -441,7 +435,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public List<AdminUserDO> getUsersByStatus(Integer status) { public List<AdminUserDO> getUserListByStatus(Integer status) {
return userMapper.selectListByStatus(status); return userMapper.selectListByStatus(status);
} }

View File

@ -64,7 +64,7 @@ public class OperateLogServiceImplTest extends BaseDbUnitTest {
o.setNickname("wang"); o.setNickname("wang");
o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setStatus(CommonStatusEnum.ENABLE.getStatus());
}); });
when(userService.getUsersByNickname("wang")).thenReturn(Collections.singletonList(user)); when(userService.getUserListByNickname("wang")).thenReturn(Collections.singletonList(user));
Long userId = user.getId(); Long userId = user.getId();
// 构造操作日志 // 构造操作日志
@ -112,7 +112,7 @@ public class OperateLogServiceImplTest extends BaseDbUnitTest {
o.setNickname("wang"); o.setNickname("wang");
o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setStatus(CommonStatusEnum.ENABLE.getStatus());
}); });
when(userService.getUsersByNickname("wang")).thenReturn(Collections.singletonList(user)); when(userService.getUserListByNickname("wang")).thenReturn(Collections.singletonList(user));
Long userId = user.getId(); Long userId = user.getId();
// 构造操作日志 // 构造操作日志

View File

@ -6,7 +6,6 @@ import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.ObjectUtils;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.infra.api.file.FileApi; import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO; import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO;
@ -32,23 +31,25 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.time.LocalDateTime;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Consumer; import java.util.function.Consumer;
import static cn.hutool.core.util.RandomUtil.randomBytes; import static cn.hutool.core.util.RandomUtil.randomBytes;
import static cn.hutool.core.util.RandomUtil.randomEle; import static cn.hutool.core.util.RandomUtil.randomEle;
import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet; import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.buildLocalDateTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime;
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime;
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
import static java.util.Collections.singleton; import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.assertj.core.util.Lists.newArrayList; import static org.assertj.core.util.Lists.newArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -173,6 +174,23 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
assertEquals(3L, userPosts.get(1).getPostId()); assertEquals(3L, userPosts.get(1).getPostId());
} }
@Test
public void testUpdateUserLogin() {
// mock 数据
AdminUserDO user = randomAdminUserDO(o -> o.setLoginDate(null));
userMapper.insert(user);
// 准备参数
Long id = user.getId();
String loginIp = randomString();
// 调用
userService.updateUserLogin(id, loginIp);
// 断言
AdminUserDO dbUser = userMapper.selectById(id);
assertEquals(loginIp, dbUser.getLoginIp());
assertNotNull(dbUser.getLoginDate());
}
@Test @Test
public void testUpdateUserProfile_success() { public void testUpdateUserProfile_success() {
// mock 数据 // mock 数据
@ -286,6 +304,34 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
verify(permissionService, times(1)).processUserDeleted(eq(userId)); verify(permissionService, times(1)).processUserDeleted(eq(userId));
} }
@Test
public void testGetUserByUsername() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO();
userMapper.insert(dbUser);
// 准备参数
String username = dbUser.getUsername();
// 调用
AdminUserDO user = userService.getUserByUsername(username);
// 断言
assertPojoEquals(dbUser, user);
}
@Test
public void testGetUserByMobile() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO();
userMapper.insert(dbUser);
// 准备参数
String mobile = dbUser.getMobile();
// 调用
AdminUserDO user = userService.getUserByMobile(mobile);
// 断言
assertPojoEquals(dbUser, user);
}
@Test @Test
public void testGetUserPage() { public void testGetUserPage() {
// mock 数据 // mock 数据
@ -295,8 +341,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
reqVO.setUsername("tu"); reqVO.setUsername("tu");
reqVO.setMobile("1560"); reqVO.setMobile("1560");
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
reqVO.setCreateTime((new LocalDateTime[]{buildLocalDateTime(2020, 12, 1), reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24));
buildLocalDateTime(2020, 12, 24)}));
reqVO.setDeptId(1L); // 其中1L 2L 的父部门 reqVO.setDeptId(1L); // 其中1L 2L 的父部门
// mock 方法 // mock 方法
List<DeptDO> deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L))); List<DeptDO> deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L)));
@ -311,7 +356,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
} }
@Test @Test
public void testGetUsers() { public void testGetUserList_export() {
// mock 数据 // mock 数据
AdminUserDO dbUser = initGetUserPageData(); AdminUserDO dbUser = initGetUserPageData();
// 准备参数 // 准备参数
@ -319,15 +364,14 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
reqVO.setUsername("tu"); reqVO.setUsername("tu");
reqVO.setMobile("1560"); reqVO.setMobile("1560");
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
reqVO.setCreateTime((new LocalDateTime[]{buildLocalDateTime(2020, 12, 1), reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24));
buildLocalDateTime(2020, 12, 24)}));
reqVO.setDeptId(1L); // 其中1L 2L 的父部门 reqVO.setDeptId(1L); // 其中1L 2L 的父部门
// mock 方法 // mock 方法
List<DeptDO> deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L))); List<DeptDO> deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L)));
when(deptService.getDeptListByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList); when(deptService.getDeptListByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList);
// 调用 // 调用
List<AdminUserDO> list = userService.getUsers(reqVO); List<AdminUserDO> list = userService.getUserList(reqVO);
// 断言 // 断言
assertEquals(1, list.size()); assertEquals(1, list.size());
assertPojoEquals(dbUser, list.get(0)); assertPojoEquals(dbUser, list.get(0));
@ -342,28 +386,59 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
o.setUsername("tudou"); o.setUsername("tudou");
o.setMobile("15601691300"); o.setMobile("15601691300");
o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setStatus(CommonStatusEnum.ENABLE.getStatus());
o.setCreateTime(buildLocalDateTime(2020, 12, 12)); o.setCreateTime(buildTime(2020, 12, 12));
o.setDeptId(2L); o.setDeptId(2L);
}); });
userMapper.insert(dbUser); userMapper.insert(dbUser);
// 测试 username 不匹配 // 测试 username 不匹配
userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setUsername("dou"))); userMapper.insert(cloneIgnoreId(dbUser, o -> o.setUsername("dou")));
// 测试 mobile 不匹配 // 测试 mobile 不匹配
userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setMobile("18818260888"))); userMapper.insert(cloneIgnoreId(dbUser, o -> o.setMobile("18818260888")));
// 测试 status 不匹配 // 测试 status 不匹配
userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); userMapper.insert(cloneIgnoreId(dbUser, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
// 测试 createTime 不匹配 // 测试 createTime 不匹配
userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setCreateTime(buildLocalDateTime(2020, 11, 11)))); userMapper.insert(cloneIgnoreId(dbUser, o -> o.setCreateTime(buildTime(2020, 11, 11))));
// 测试 dept 不匹配 // 测试 dept 不匹配
userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setDeptId(0L))); userMapper.insert(cloneIgnoreId(dbUser, o -> o.setDeptId(0L)));
return dbUser; return dbUser;
} }
@Test
public void testGetUser() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO();
userMapper.insert(dbUser);
// 准备参数
Long userId = dbUser.getId();
// 调用
AdminUserDO user = userService.getUser(userId);
// 断言
assertPojoEquals(dbUser, user);
}
@Test
public void testGetUserListByDeptIds() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO(o -> o.setDeptId(1L));
userMapper.insert(dbUser);
// 测试 deptId 不匹配
userMapper.insert(cloneIgnoreId(dbUser, o -> o.setDeptId(2L)));
// 准备参数
Collection<Long> deptIds = singleton(1L);
// 调用
List<AdminUserDO> list = userService.getUserListByDeptIds(deptIds);
// 断言
assertEquals(1, list.size());
assertEquals(dbUser, list.get(0));
}
/** /**
* 情况一校验不通过导致插入失败 * 情况一校验不通过导致插入失败
*/ */
@Test @Test
public void testImportUsers_01() { public void testImportUserList_01() {
// 准备参数 // 准备参数
UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
}); });
@ -371,7 +446,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
doThrow(new ServiceException(DEPT_NOT_FOUND)).when(deptService).validateDeptList(any()); doThrow(new ServiceException(DEPT_NOT_FOUND)).when(deptService).validateDeptList(any());
// 调用 // 调用
UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true); UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true);
// 断言 // 断言
assertEquals(0, respVO.getCreateUsernames().size()); assertEquals(0, respVO.getCreateUsernames().size());
assertEquals(0, respVO.getUpdateUsernames().size()); assertEquals(0, respVO.getUpdateUsernames().size());
@ -383,7 +458,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
* 情况二不存在进行插入 * 情况二不存在进行插入
*/ */
@Test @Test
public void testImportUsers_02() { public void testImportUserList_02() {
// 准备参数 // 准备参数
UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
@ -399,7 +474,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
when(passwordEncoder.encode(eq("yudaoyuanma"))).thenReturn("java"); when(passwordEncoder.encode(eq("yudaoyuanma"))).thenReturn("java");
// 调用 // 调用
UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true); UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true);
// 断言 // 断言
assertEquals(1, respVO.getCreateUsernames().size()); assertEquals(1, respVO.getCreateUsernames().size());
AdminUserDO user = userMapper.selectByUsername(respVO.getCreateUsernames().get(0)); AdminUserDO user = userMapper.selectByUsername(respVO.getCreateUsernames().get(0));
@ -413,7 +488,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
* 情况三存在但是不强制更新 * 情况三存在但是不强制更新
*/ */
@Test @Test
public void testImportUsers_03() { public void testImportUserList_03() {
// mock 数据 // mock 数据
AdminUserDO dbUser = randomAdminUserDO(); AdminUserDO dbUser = randomAdminUserDO();
userMapper.insert(dbUser); userMapper.insert(dbUser);
@ -431,7 +506,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
when(deptService.getDept(eq(dept.getId()))).thenReturn(dept); when(deptService.getDept(eq(dept.getId()))).thenReturn(dept);
// 调用 // 调用
UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), false); UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), false);
// 断言 // 断言
assertEquals(0, respVO.getCreateUsernames().size()); assertEquals(0, respVO.getCreateUsernames().size());
assertEquals(0, respVO.getUpdateUsernames().size()); assertEquals(0, respVO.getUpdateUsernames().size());
@ -443,7 +518,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
* 情况四存在强制更新 * 情况四存在强制更新
*/ */
@Test @Test
public void testImportUsers_04() { public void testImportUserList_04() {
// mock 数据 // mock 数据
AdminUserDO dbUser = randomAdminUserDO(); AdminUserDO dbUser = randomAdminUserDO();
userMapper.insert(dbUser); userMapper.insert(dbUser);
@ -461,7 +536,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
when(deptService.getDept(eq(dept.getId()))).thenReturn(dept); when(deptService.getDept(eq(dept.getId()))).thenReturn(dept);
// 调用 // 调用
UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true); UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true);
// 断言 // 断言
assertEquals(0, respVO.getCreateUsernames().size()); assertEquals(0, respVO.getCreateUsernames().size());
assertEquals(1, respVO.getUpdateUsernames().size()); assertEquals(1, respVO.getUpdateUsernames().size());
@ -471,24 +546,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
} }
@Test @Test
public void testCheckUserExists_notExists() { public void testValidateUserExists_notExists() {
assertServiceException(() -> userService.checkUserExists(randomLongId()), USER_NOT_EXISTS); assertServiceException(() -> userService.validateUserExists(randomLongId()), USER_NOT_EXISTS);
} }
@Test @Test
public void testCheckUsernameUnique_usernameExistsForCreate() { public void testValidateUsernameUnique_usernameExistsForCreate() {
// 准备参数 // 准备参数
String username = randomString(); String username = randomString();
// mock 数据 // mock 数据
userMapper.insert(randomAdminUserDO(o -> o.setUsername(username))); userMapper.insert(randomAdminUserDO(o -> o.setUsername(username)));
// 调用校验异常 // 调用校验异常
assertServiceException(() -> userService.checkUsernameUnique(null, username), assertServiceException(() -> userService.validateUsernameUnique(null, username),
USER_USERNAME_EXISTS); USER_USERNAME_EXISTS);
} }
@Test @Test
public void testCheckUsernameUnique_usernameExistsForUpdate() { public void testValidateUsernameUnique_usernameExistsForUpdate() {
// 准备参数 // 准备参数
Long id = randomLongId(); Long id = randomLongId();
String username = randomString(); String username = randomString();
@ -496,24 +571,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
userMapper.insert(randomAdminUserDO(o -> o.setUsername(username))); userMapper.insert(randomAdminUserDO(o -> o.setUsername(username)));
// 调用校验异常 // 调用校验异常
assertServiceException(() -> userService.checkUsernameUnique(id, username), assertServiceException(() -> userService.validateUsernameUnique(id, username),
USER_USERNAME_EXISTS); USER_USERNAME_EXISTS);
} }
@Test @Test
public void testCheckEmailUnique_emailExistsForCreate() { public void testValidateEmailUnique_emailExistsForCreate() {
// 准备参数 // 准备参数
String email = randomString(); String email = randomString();
// mock 数据 // mock 数据
userMapper.insert(randomAdminUserDO(o -> o.setEmail(email))); userMapper.insert(randomAdminUserDO(o -> o.setEmail(email)));
// 调用校验异常 // 调用校验异常
assertServiceException(() -> userService.checkEmailUnique(null, email), assertServiceException(() -> userService.validateEmailUnique(null, email),
USER_EMAIL_EXISTS); USER_EMAIL_EXISTS);
} }
@Test @Test
public void testCheckEmailUnique_emailExistsForUpdate() { public void testValidateEmailUnique_emailExistsForUpdate() {
// 准备参数 // 准备参数
Long id = randomLongId(); Long id = randomLongId();
String email = randomString(); String email = randomString();
@ -521,24 +596,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
userMapper.insert(randomAdminUserDO(o -> o.setEmail(email))); userMapper.insert(randomAdminUserDO(o -> o.setEmail(email)));
// 调用校验异常 // 调用校验异常
assertServiceException(() -> userService.checkEmailUnique(id, email), assertServiceException(() -> userService.validateEmailUnique(id, email),
USER_EMAIL_EXISTS); USER_EMAIL_EXISTS);
} }
@Test @Test
public void testCheckMobileUnique_mobileExistsForCreate() { public void testValidateMobileUnique_mobileExistsForCreate() {
// 准备参数 // 准备参数
String mobile = randomString(); String mobile = randomString();
// mock 数据 // mock 数据
userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile))); userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile)));
// 调用校验异常 // 调用校验异常
assertServiceException(() -> userService.checkMobileUnique(null, mobile), assertServiceException(() -> userService.validateMobileUnique(null, mobile),
USER_MOBILE_EXISTS); USER_MOBILE_EXISTS);
} }
@Test @Test
public void testCheckMobileUnique_mobileExistsForUpdate() { public void testValidateMobileUnique_mobileExistsForUpdate() {
// 准备参数 // 准备参数
Long id = randomLongId(); Long id = randomLongId();
String mobile = randomString(); String mobile = randomString();
@ -546,18 +621,18 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile))); userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile)));
// 调用校验异常 // 调用校验异常
assertServiceException(() -> userService.checkMobileUnique(id, mobile), assertServiceException(() -> userService.validateMobileUnique(id, mobile),
USER_MOBILE_EXISTS); USER_MOBILE_EXISTS);
} }
@Test @Test
public void testCheckOldPassword_notExists() { public void testValidateOldPassword_notExists() {
assertServiceException(() -> userService.checkOldPassword(randomLongId(), randomString()), assertServiceException(() -> userService.validateOldPassword(randomLongId(), randomString()),
USER_NOT_EXISTS); USER_NOT_EXISTS);
} }
@Test @Test
public void testCheckOldPassword_passwordFailed() { public void testValidateOldPassword_passwordFailed() {
// mock 数据 // mock 数据
AdminUserDO user = randomAdminUserDO(); AdminUserDO user = randomAdminUserDO();
userMapper.insert(user); userMapper.insert(user);
@ -566,14 +641,14 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
String oldPassword = user.getPassword(); String oldPassword = user.getPassword();
// 调用校验异常 // 调用校验异常
assertServiceException(() -> userService.checkOldPassword(id, oldPassword), assertServiceException(() -> userService.validateOldPassword(id, oldPassword),
USER_PASSWORD_FAILED); USER_PASSWORD_FAILED);
// 校验调用 // 校验调用
verify(passwordEncoder, times(1)).matches(eq(oldPassword), eq(user.getPassword())); verify(passwordEncoder, times(1)).matches(eq(oldPassword), eq(user.getPassword()));
} }
@Test @Test
public void testUsersByPostIds() { public void testUserListByPostIds() {
// 准备参数 // 准备参数
Collection<Long> postIds = asSet(10L, 20L); Collection<Long> postIds = asSet(10L, 20L);
// mock user1 数据 // mock user1 数据
@ -587,12 +662,114 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
userPostMapper.insert(new UserPostDO().setUserId(user2.getId()).setPostId(100L)); userPostMapper.insert(new UserPostDO().setUserId(user2.getId()).setPostId(100L));
// 调用 // 调用
List<AdminUserDO> result = userService.getUsersByPostIds(postIds); List<AdminUserDO> result = userService.getUserListByPostIds(postIds);
// 断言 // 断言
assertEquals(1, result.size()); assertEquals(1, result.size());
assertEquals(user1, result.get(0)); assertEquals(user1, result.get(0));
} }
@Test
public void testGetUserList() {
// mock 数据
AdminUserDO user = randomAdminUserDO();
userMapper.insert(user);
// 测试 id 不匹配
userMapper.insert(randomAdminUserDO());
// 准备参数
Collection<Long> ids = singleton(user.getId());
// 调用
List<AdminUserDO> result = userService.getUserList(ids);
// 断言
assertEquals(1, result.size());
assertEquals(user, result.get(0));
}
@Test
public void testGetUserMap() {
// mock 数据
AdminUserDO user = randomAdminUserDO();
userMapper.insert(user);
// 测试 id 不匹配
userMapper.insert(randomAdminUserDO());
// 准备参数
Collection<Long> ids = singleton(user.getId());
// 调用
Map<Long, AdminUserDO> result = userService.getUserMap(ids);
// 断言
assertEquals(1, result.size());
assertEquals(user, result.get(user.getId()));
}
@Test
public void testGetUserListByNickname() {
// mock 数据
AdminUserDO user = randomAdminUserDO(o -> o.setNickname("芋头"));
userMapper.insert(user);
// 测试 nickname 不匹配
userMapper.insert(randomAdminUserDO(o -> o.setNickname("源码")));
// 准备参数
String nickname = "";
// 调用
List<AdminUserDO> result = userService.getUserListByNickname(nickname);
// 断言
assertEquals(1, result.size());
assertEquals(user, result.get(0));
}
@Test
public void testGetUserListByStatus() {
// mock 数据
AdminUserDO user = randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()));
userMapper.insert(user);
// 测试 status 不匹配
userMapper.insert(randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())));
// 准备参数
Integer status = CommonStatusEnum.DISABLE.getStatus();
// 调用
List<AdminUserDO> result = userService.getUserListByStatus(status);
// 断言
assertEquals(1, result.size());
assertEquals(user, result.get(0));
}
@Test
public void testValidateUserList_success() {
// mock 数据
AdminUserDO userDO = randomAdminUserDO().setStatus(CommonStatusEnum.ENABLE.getStatus());
userMapper.insert(userDO);
// 准备参数
List<Long> ids = singletonList(userDO.getId());
// 调用无需断言
userService.validateUserList(ids);
}
@Test
public void testValidateUserList_notFound() {
// 准备参数
List<Long> ids = singletonList(randomLongId());
// 调用, 并断言异常
assertServiceException(() -> userService.validateUserList(ids), USER_NOT_EXISTS);
}
@Test
public void testValidateUserList_notEnable() {
// mock 数据
AdminUserDO userDO = randomAdminUserDO().setStatus(CommonStatusEnum.DISABLE.getStatus());
userMapper.insert(userDO);
// 准备参数
List<Long> ids = singletonList(userDO.getId());
// 调用, 并断言异常
assertServiceException(() -> userService.validateUserList(ids), USER_IS_DISABLE,
userDO.getNickname());
}
// ========== 随机对象 ========== // ========== 随机对象 ==========
@SafeVarargs @SafeVarargs