完善 DeptServiceImpl 单元测试

This commit is contained in:
YunaiV 2023-02-01 00:07:28 +08:00
parent 2edf53a403
commit 7f6d64e921
12 changed files with 187 additions and 127 deletions

View File

@ -216,7 +216,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {
roleApi.validRoles(options); roleApi.validRoles(options);
} else if (ObjectUtils.equalsAny(type, BpmTaskAssignRuleTypeEnum.DEPT_MEMBER.getType(), } else if (ObjectUtils.equalsAny(type, BpmTaskAssignRuleTypeEnum.DEPT_MEMBER.getType(),
BpmTaskAssignRuleTypeEnum.DEPT_LEADER.getType())) { BpmTaskAssignRuleTypeEnum.DEPT_LEADER.getType())) {
deptApi.validDepts(options); deptApi.validateDeptList(options);
} else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.POST.getType())) { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.POST.getType())) {
postApi.validPosts(options); postApi.validPosts(options);
} else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER.getType())) { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER.getType())) {
@ -293,7 +293,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {
} }
private Set<Long> calculateTaskCandidateUsersByDeptLeader(BpmTaskAssignRuleDO rule) { private Set<Long> calculateTaskCandidateUsersByDeptLeader(BpmTaskAssignRuleDO rule) {
List<DeptRespDTO> depts = deptApi.getDepts(rule.getOptions()).getCheckedData(); List<DeptRespDTO> depts = deptApi.getDeptList(rule.getOptions()).getCheckedData();
return convertSet(depts, DeptRespDTO::getLeaderUserId); return convertSet(depts, DeptRespDTO::getLeaderUserId);
} }

View File

@ -104,7 +104,7 @@ public class BpmTaskAssignRuleServiceImplTest extends BaseDbUnitTest {
// mock 方法 // mock 方法
DeptRespDTO dept1 = randomPojo(DeptRespDTO.class, o -> o.setLeaderUserId(11L)); DeptRespDTO dept1 = randomPojo(DeptRespDTO.class, o -> o.setLeaderUserId(11L));
DeptRespDTO dept2 = randomPojo(DeptRespDTO.class, o -> o.setLeaderUserId(22L)); DeptRespDTO dept2 = randomPojo(DeptRespDTO.class, o -> o.setLeaderUserId(22L));
when(deptApi.getDepts(eq(rule.getOptions()))).thenReturn(success(Arrays.asList(dept1, dept2))); when(deptApi.getDeptList(eq(rule.getOptions()))).thenReturn(success(Arrays.asList(dept1, dept2)));
mockGetUserMap(asSet(11L, 22L)); mockGetUserMap(asSet(11L, 22L));
// 调用 // 调用

View File

@ -30,12 +30,12 @@ public interface DeptApi {
@GetMapping(PREFIX + "/list") @GetMapping(PREFIX + "/list")
@ApiOperation("获得部门信息数组") @ApiOperation("获得部门信息数组")
@ApiImplicitParam(name = "ids", value = "部门编号数组", example = "1,2", required = true, allowMultiple = true) @ApiImplicitParam(name = "ids", value = "部门编号数组", example = "1,2", required = true, allowMultiple = true)
CommonResult<List<DeptRespDTO>> getDepts(@RequestParam("ids") Collection<Long> ids); CommonResult<List<DeptRespDTO>> getDeptList(@RequestParam("ids") Collection<Long> ids);
@GetMapping(PREFIX + "/valid") @GetMapping(PREFIX + "/valid")
@ApiOperation("校验部门是否合法") @ApiOperation("校验部门是否合法")
@ApiImplicitParam(name = "ids", value = "部门编号数组", example = "1,2", required = true, allowMultiple = true) @ApiImplicitParam(name = "ids", value = "部门编号数组", example = "1,2", required = true, allowMultiple = true)
CommonResult<Boolean> validDepts(@RequestParam("ids") Collection<Long> ids); CommonResult<Boolean> validateDeptList(@RequestParam("ids") Collection<Long> ids);
/** /**
* 获得指定编号的部门 Map * 获得指定编号的部门 Map
@ -44,7 +44,7 @@ public interface DeptApi {
* @return 部门 Map * @return 部门 Map
*/ */
default Map<Long, DeptRespDTO> getDeptMap(Set<Long> ids) { default Map<Long, DeptRespDTO> getDeptMap(Set<Long> ids) {
return CollectionUtils.convertMap(getDepts(ids).getCheckedData(), DeptRespDTO::getId); return CollectionUtils.convertMap(getDeptList(ids).getCheckedData(), DeptRespDTO::getId);
} }
} }

View File

@ -31,14 +31,14 @@ public class DeptApiImpl implements DeptApi {
} }
@Override @Override
public CommonResult<List<DeptRespDTO>> getDepts(Collection<Long> ids) { public CommonResult<List<DeptRespDTO>> getDeptList(Collection<Long> ids) {
List<DeptDO> depts = deptService.getDepts(ids); List<DeptDO> depts = deptService.getDeptList(ids);
return success(DeptConvert.INSTANCE.convertList03(depts)); return success(DeptConvert.INSTANCE.convertList03(depts));
} }
@Override @Override
public CommonResult<Boolean> validDepts(Collection<Long> ids) { public CommonResult<Boolean> validateDeptList(Collection<Long> ids) {
deptService.validDepts(ids); deptService.validateDeptList(ids);
return success(true); return success(true);
} }

View File

@ -58,7 +58,7 @@ public class DeptController {
@ApiOperation("获取部门列表") @ApiOperation("获取部门列表")
@PreAuthorize("@ss.hasPermission('system:dept:query')") @PreAuthorize("@ss.hasPermission('system:dept:query')")
public CommonResult<List<DeptRespVO>> listDepts(DeptListReqVO reqVO) { public CommonResult<List<DeptRespVO>> listDepts(DeptListReqVO reqVO) {
List<DeptDO> list = deptService.getSimpleDepts(reqVO); List<DeptDO> list = deptService.getDeptList(reqVO);
list.sort(Comparator.comparing(DeptDO::getSort)); list.sort(Comparator.comparing(DeptDO::getSort));
return success(DeptConvert.INSTANCE.convertList(list)); return success(DeptConvert.INSTANCE.convertList(list));
} }
@ -69,7 +69,7 @@ public class DeptController {
// 获得部门列表只要开启状态的 // 获得部门列表只要开启状态的
DeptListReqVO reqVO = new DeptListReqVO(); DeptListReqVO reqVO = new DeptListReqVO();
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
List<DeptDO> list = deptService.getSimpleDepts(reqVO); List<DeptDO> list = deptService.getDeptList(reqVO);
// 排序后返回给前端 // 排序后返回给前端
list.sort(Comparator.comparing(DeptDO::getSort)); list.sort(Comparator.comparing(DeptDO::getSort));
return success(DeptConvert.INSTANCE.convertList02(list)); return success(DeptConvert.INSTANCE.convertList02(list));

View File

@ -52,7 +52,7 @@ public interface DeptService {
* @param reqVO 筛选条件请求 VO * @param reqVO 筛选条件请求 VO
* @return 部门列表 * @return 部门列表
*/ */
List<DeptDO> getSimpleDepts(DeptListReqVO reqVO); List<DeptDO> getDeptList(DeptListReqVO reqVO);
/** /**
* 获得所有子部门从缓存中 * 获得所有子部门从缓存中
@ -61,7 +61,7 @@ public interface DeptService {
* @param recursive 是否递归获取所有 * @param recursive 是否递归获取所有
* @return 子部门列表 * @return 子部门列表
*/ */
List<DeptDO> getDeptsByParentIdFromCache(Long parentId, boolean recursive); List<DeptDO> getDeptListByParentIdFromCache(Long parentId, boolean recursive);
/** /**
* 获得部门信息数组 * 获得部门信息数组
@ -69,7 +69,21 @@ public interface DeptService {
* @param ids 部门编号数组 * @param ids 部门编号数组
* @return 部门信息数组 * @return 部门信息数组
*/ */
List<DeptDO> getDepts(Collection<Long> ids); List<DeptDO> getDeptList(Collection<Long> ids);
/**
* 获得指定编号的部门 Map
*
* @param ids 部门编号数组
* @return 部门 Map
*/
default Map<Long, DeptDO> getDeptMap(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return Collections.emptyMap();
}
List<DeptDO> list = getDeptList(ids);
return CollectionUtils.convertMap(list, DeptDO::getId);
}
/** /**
* 获得部门信息 * 获得部门信息
@ -86,27 +100,6 @@ public interface DeptService {
* *
* @param ids 角色编号数组 * @param ids 角色编号数组
*/ */
void validDepts(Collection<Long> ids); void validateDeptList(Collection<Long> ids);
/**
* 获得指定编号的部门列表
*
* @param ids 部门编号数组
* @return 部门列表
*/
List<DeptDO> getSimpleDepts(Collection<Long> ids);
/**
* 获得指定编号的部门 Map
*
* @param ids 部门编号数组
* @return 部门 Map
*/
default Map<Long, DeptDO> getDeptMap(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return Collections.emptyMap();
}
List<DeptDO> list = getSimpleDepts(ids);
return CollectionUtils.convertMap(list, DeptDO::getId);
}
} }

View File

@ -2,8 +2,6 @@ package cn.iocoder.yudao.module.system.service.dept;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils; import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptCreateReqVO;
@ -19,13 +17,11 @@ import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import lombok.Getter; import lombok.Getter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*; import java.util.*;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
@ -95,7 +91,7 @@ public class DeptServiceImpl implements DeptService {
if (reqVO.getParentId() == null) { if (reqVO.getParentId() == null) {
reqVO.setParentId(DeptIdEnum.ROOT.getId()); reqVO.setParentId(DeptIdEnum.ROOT.getId());
} }
checkCreateOrUpdate(null, reqVO.getParentId(), reqVO.getName()); validateForCreateOrUpdate(null, reqVO.getParentId(), reqVO.getName());
// 插入部门 // 插入部门
DeptDO dept = DeptConvert.INSTANCE.convert(reqVO); DeptDO dept = DeptConvert.INSTANCE.convert(reqVO);
deptMapper.insert(dept); deptMapper.insert(dept);
@ -110,7 +106,7 @@ public class DeptServiceImpl implements DeptService {
if (reqVO.getParentId() == null) { if (reqVO.getParentId() == null) {
reqVO.setParentId(DeptIdEnum.ROOT.getId()); reqVO.setParentId(DeptIdEnum.ROOT.getId());
} }
checkCreateOrUpdate(reqVO.getId(), reqVO.getParentId(), reqVO.getName()); validateForCreateOrUpdate(reqVO.getId(), reqVO.getParentId(), reqVO.getName());
// 更新部门 // 更新部门
DeptDO updateObj = DeptConvert.INSTANCE.convert(reqVO); DeptDO updateObj = DeptConvert.INSTANCE.convert(reqVO);
deptMapper.updateById(updateObj); deptMapper.updateById(updateObj);
@ -121,10 +117,10 @@ public class DeptServiceImpl implements DeptService {
@Override @Override
public void deleteDept(Long id) { public void deleteDept(Long id) {
// 校验是否存在 // 校验是否存在
checkDeptExists(id); validateDeptExists(id);
// 校验是否有子部门 // 校验是否有子部门
if (deptMapper.selectCountByParentId(id) > 0) { if (deptMapper.selectCountByParentId(id) > 0) {
throw ServiceExceptionUtil.exception(DEPT_EXITS_CHILDREN); throw exception(DEPT_EXITS_CHILDREN);
} }
// 删除部门 // 删除部门
deptMapper.deleteById(id); deptMapper.deleteById(id);
@ -133,16 +129,16 @@ public class DeptServiceImpl implements DeptService {
} }
@Override @Override
public List<DeptDO> getSimpleDepts(DeptListReqVO reqVO) { public List<DeptDO> getDeptList(DeptListReqVO reqVO) {
return deptMapper.selectList(reqVO); return deptMapper.selectList(reqVO);
} }
@Override @Override
public List<DeptDO> getDeptsByParentIdFromCache(Long parentId, boolean recursive) { public List<DeptDO> getDeptListByParentIdFromCache(Long parentId, boolean recursive) {
if (parentId == null) { if (parentId == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
List<DeptDO> result = new ArrayList<>(); // TODO 芋艿待优化新增缓存避免每次遍历的计算 List<DeptDO> result = new ArrayList<>();
// 递归简单粗暴 // 递归简单粗暴
this.getDeptsByParentIdFromCache(result, parentId, this.getDeptsByParentIdFromCache(result, parentId,
recursive ? Integer.MAX_VALUE : 1, // 如果递归获取则无限否则只递归 1 recursive ? Integer.MAX_VALUE : 1, // 如果递归获取则无限否则只递归 1
@ -182,65 +178,65 @@ public class DeptServiceImpl implements DeptService {
recursiveCount - 1, parentDeptMap)); recursiveCount - 1, parentDeptMap));
} }
private void checkCreateOrUpdate(Long id, Long parentId, String name) { private void validateForCreateOrUpdate(Long id, Long parentId, String name) {
// 校验自己存在 // 校验自己存在
checkDeptExists(id); validateDeptExists(id);
// 校验父部门的有效性 // 校验父部门的有效性
checkParentDeptEnable(id, parentId); validateParentDeptEnable(id, parentId);
// 校验部门名的唯一性 // 校验部门名的唯一性
checkDeptNameUnique(id, parentId, name); validateDeptNameUnique(id, parentId, name);
} }
private void checkParentDeptEnable(Long id, Long parentId) { private void validateParentDeptEnable(Long id, Long parentId) {
if (parentId == null || DeptIdEnum.ROOT.getId().equals(parentId)) { if (parentId == null || DeptIdEnum.ROOT.getId().equals(parentId)) {
return; return;
} }
// 不能设置自己为父部门 // 不能设置自己为父部门
if (parentId.equals(id)) { if (parentId.equals(id)) {
throw ServiceExceptionUtil.exception(DEPT_PARENT_ERROR); throw exception(DEPT_PARENT_ERROR);
} }
// 父岗位不存在 // 父岗位不存在
DeptDO dept = deptMapper.selectById(parentId); DeptDO dept = deptMapper.selectById(parentId);
if (dept == null) { if (dept == null) {
throw ServiceExceptionUtil.exception(DEPT_PARENT_NOT_EXITS); throw exception(DEPT_PARENT_NOT_EXITS);
} }
// 父部门被禁用 // 父部门被禁用
if (!CommonStatusEnum.ENABLE.getStatus().equals(dept.getStatus())) { if (!CommonStatusEnum.ENABLE.getStatus().equals(dept.getStatus())) {
throw ServiceExceptionUtil.exception(DEPT_NOT_ENABLE); throw exception(DEPT_NOT_ENABLE);
} }
// 父部门不能是原来的子部门 // 父部门不能是原来的子部门
List<DeptDO> children = this.getDeptsByParentIdFromCache(id, true); List<DeptDO> children = this.getDeptListByParentIdFromCache(id, true);
if (children.stream().anyMatch(dept1 -> dept1.getId().equals(parentId))) { if (children.stream().anyMatch(dept1 -> dept1.getId().equals(parentId))) {
throw ServiceExceptionUtil.exception(DEPT_PARENT_IS_CHILD); throw exception(DEPT_PARENT_IS_CHILD);
} }
} }
private void checkDeptExists(Long id) { private void validateDeptExists(Long id) {
if (id == null) { if (id == null) {
return; return;
} }
DeptDO dept = deptMapper.selectById(id); DeptDO dept = deptMapper.selectById(id);
if (dept == null) { if (dept == null) {
throw ServiceExceptionUtil.exception(DEPT_NOT_FOUND); throw exception(DEPT_NOT_FOUND);
} }
} }
private void checkDeptNameUnique(Long id, Long parentId, String name) { private void validateDeptNameUnique(Long id, Long parentId, String name) {
DeptDO menu = deptMapper.selectByParentIdAndName(parentId, name); DeptDO menu = deptMapper.selectByParentIdAndName(parentId, name);
if (menu == null) { if (menu == null) {
return; return;
} }
// 如果 id 为空说明不用比较是否为相同 id 的岗位 // 如果 id 为空说明不用比较是否为相同 id 的岗位
if (id == null) { if (id == null) {
throw ServiceExceptionUtil.exception(DEPT_NAME_DUPLICATE); throw exception(DEPT_NAME_DUPLICATE);
} }
if (!menu.getId().equals(id)) { if (!menu.getId().equals(id)) {
throw ServiceExceptionUtil.exception(DEPT_NAME_DUPLICATE); throw exception(DEPT_NAME_DUPLICATE);
} }
} }
@Override @Override
public List<DeptDO> getDepts(Collection<Long> ids) { public List<DeptDO> getDeptList(Collection<Long> ids) {
return deptMapper.selectBatchIds(ids); return deptMapper.selectBatchIds(ids);
} }
@ -250,13 +246,12 @@ public class DeptServiceImpl implements DeptService {
} }
@Override @Override
public void validDepts(Collection<Long> ids) { public void validateDeptList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) { if (CollUtil.isEmpty(ids)) {
return; return;
} }
// 获得科室信息 // 获得科室信息
List<DeptDO> depts = deptMapper.selectBatchIds(ids); Map<Long, DeptDO> deptMap = getDeptMap(ids);
Map<Long, DeptDO> deptMap = CollectionUtils.convertMap(depts, DeptDO::getId);
// 校验 // 校验
ids.forEach(id -> { ids.forEach(id -> {
DeptDO dept = deptMap.get(id); DeptDO dept = deptMap.get(id);
@ -269,9 +264,4 @@ public class DeptServiceImpl implements DeptService {
}); });
} }
@Override
public List<DeptDO> getSimpleDepts(Collection<Long> ids) {
return deptMapper.selectBatchIds(ids);
}
} }

View File

@ -418,7 +418,7 @@ public class PermissionServiceImpl implements PermissionService {
} }
// 情况四DEPT_DEPT_AND_CHILD // 情况四DEPT_DEPT_AND_CHILD
if (Objects.equals(role.getDataScope(), DataScopeEnum.DEPT_AND_CHILD.getScope())) { if (Objects.equals(role.getDataScope(), DataScopeEnum.DEPT_AND_CHILD.getScope())) {
List<DeptDO> depts = deptService.getDeptsByParentIdFromCache(userDeptIdCache.get(), true); List<DeptDO> depts = deptService.getDeptListByParentIdFromCache(userDeptIdCache.get(), true);
CollUtil.addAll(result.getDeptIds(), CollectionUtils.convertList(depts, DeptDO::getId)); CollUtil.addAll(result.getDeptIds(), CollectionUtils.convertList(depts, DeptDO::getId));
// 添加本身部门编号 // 添加本身部门编号
CollUtil.addAll(result.getDeptIds(), userDeptIdCache.get()); CollUtil.addAll(result.getDeptIds(), userDeptIdCache.get());

View File

@ -298,7 +298,7 @@ public class AdminUserServiceImpl implements AdminUserService {
if (deptId == null) { if (deptId == null) {
return Collections.emptySet(); return Collections.emptySet();
} }
Set<Long> deptIds = convertSet(deptService.getDeptsByParentIdFromCache( Set<Long> deptIds = convertSet(deptService.getDeptListByParentIdFromCache(
deptId, true), DeptDO::getId); deptId, true), DeptDO::getId);
deptIds.add(deptId); // 包括自身 deptIds.add(deptId); // 包括自身
return deptIds; return deptIds;
@ -316,7 +316,7 @@ public class AdminUserServiceImpl implements AdminUserService {
// 校验邮箱唯一 // 校验邮箱唯一
checkEmailUnique(id, email); checkEmailUnique(id, email);
// 校验部门处于开启状态 // 校验部门处于开启状态
deptService.validDepts(CollectionUtils.singleton(deptId)); deptService.validateDeptList(CollectionUtils.singleton(deptId));
// 校验岗位处于开启状态 // 校验岗位处于开启状态
postService.validPosts(postIds); postService.validPosts(postIds);
} }

View File

@ -19,6 +19,7 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -28,8 +29,8 @@ import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEq
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.singletonList;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
/** /**
@ -38,7 +39,7 @@ import static org.mockito.Mockito.verify;
* @author niudehua * @author niudehua
*/ */
@Import(DeptServiceImpl.class) @Import(DeptServiceImpl.class)
public class DeptServiceTest extends BaseDbUnitTest { public class DeptServiceImplTest extends BaseDbUnitTest {
@Resource @Resource
private DeptServiceImpl deptService; private DeptServiceImpl deptService;
@ -76,7 +77,7 @@ public class DeptServiceTest extends BaseDbUnitTest {
} }
@Test @Test
void testListDepts() { public void testListDepts() {
// mock 数据 // mock 数据
DeptDO dept = randomPojo(DeptDO.class, o -> { // 等会查询到 DeptDO dept = randomPojo(DeptDO.class, o -> { // 等会查询到
o.setName("开发部"); o.setName("开发部");
@ -91,21 +92,22 @@ public class DeptServiceTest extends BaseDbUnitTest {
DeptListReqVO reqVO = new DeptListReqVO(); DeptListReqVO reqVO = new DeptListReqVO();
reqVO.setName(""); reqVO.setName("");
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
// 调用 // 调用
List<DeptDO> sysDeptDOS = deptService.getSimpleDepts(reqVO); List<DeptDO> sysDeptDOS = deptService.getDeptList(reqVO);
// 断言 // 断言
assertEquals(1, sysDeptDOS.size()); assertEquals(1, sysDeptDOS.size());
assertPojoEquals(dept, sysDeptDOS.get(0)); assertPojoEquals(dept, sysDeptDOS.get(0));
} }
@Test @Test
void testCreateDept_success() { public void testCreateDept_success() {
// 准备参数 // 准备参数
DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class, DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class, o -> {
o -> {
o.setParentId(DeptIdEnum.ROOT.getId()); o.setParentId(DeptIdEnum.ROOT.getId());
o.setStatus(randomCommonStatus()); o.setStatus(randomCommonStatus());
}); });
// 调用 // 调用
Long deptId = deptService.createDept(reqVO); Long deptId = deptService.createDept(reqVO);
// 断言 // 断言
@ -114,11 +116,11 @@ public class DeptServiceTest extends BaseDbUnitTest {
DeptDO deptDO = deptMapper.selectById(deptId); DeptDO deptDO = deptMapper.selectById(deptId);
assertPojoEquals(reqVO, deptDO); assertPojoEquals(reqVO, deptDO);
// 校验调用 // 校验调用
verify(deptProducer, times(1)).sendDeptRefreshMessage(); verify(deptProducer).sendDeptRefreshMessage();
} }
@Test @Test
void testUpdateDept_success() { public void testUpdateDept_success() {
// mock 数据 // mock 数据
DeptDO dbDeptDO = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus())); DeptDO dbDeptDO = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus()));
deptMapper.insert(dbDeptDO);// @Sql: 先插入出一条存在的数据 deptMapper.insert(dbDeptDO);// @Sql: 先插入出一条存在的数据
@ -129,28 +131,34 @@ public class DeptServiceTest extends BaseDbUnitTest {
o.setId(dbDeptDO.getId()); o.setId(dbDeptDO.getId());
o.setStatus(randomCommonStatus()); o.setStatus(randomCommonStatus());
}); });
// 调用 // 调用
deptService.updateDept(reqVO); deptService.updateDept(reqVO);
// 校验是否更新正确 // 校验是否更新正确
DeptDO deptDO = deptMapper.selectById(reqVO.getId()); // 获取最新的 DeptDO deptDO = deptMapper.selectById(reqVO.getId()); // 获取最新的
assertPojoEquals(reqVO, deptDO); assertPojoEquals(reqVO, deptDO);
// 校验调用
verify(deptProducer).sendDeptRefreshMessage();
} }
@Test @Test
void testDeleteDept_success() { public void testDeleteDept_success() {
// mock 数据 // mock 数据
DeptDO dbDeptDO = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus())); DeptDO dbDeptDO = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus()));
deptMapper.insert(dbDeptDO);// @Sql: 先插入出一条存在的数据 deptMapper.insert(dbDeptDO);// @Sql: 先插入出一条存在的数据
// 准备参数 // 准备参数
Long id = dbDeptDO.getId(); Long id = dbDeptDO.getId();
// 调用 // 调用
deptService.deleteDept(id); deptService.deleteDept(id);
// 校验数据不存在了 // 校验数据不存在了
assertNull(deptMapper.selectById(id)); assertNull(deptMapper.selectById(id));
// 校验调用
verify(deptProducer).sendDeptRefreshMessage();
} }
@Test @Test
void testCheckDept_nameDuplicateForUpdate() { public void testValidateDept_nameDuplicateForUpdate() {
// mock 数据 // mock 数据
DeptDO deptDO = randomDeptDO(); DeptDO deptDO = randomDeptDO();
// 设置根节点部门 // 设置根节点部门
@ -162,8 +170,7 @@ public class DeptServiceTest extends BaseDbUnitTest {
nameDeptDO.setParentId(DeptIdEnum.ROOT.getId()); nameDeptDO.setParentId(DeptIdEnum.ROOT.getId());
deptMapper.insert(nameDeptDO); deptMapper.insert(nameDeptDO);
// 准备参数 // 准备参数
DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, o -> {
o -> {
// 设置根节点部门 // 设置根节点部门
o.setParentId(DeptIdEnum.ROOT.getId()); o.setParentId(DeptIdEnum.ROOT.getId());
// 设置更新的 ID // 设置更新的 ID
@ -171,28 +178,32 @@ public class DeptServiceTest extends BaseDbUnitTest {
// 模拟 name 重复 // 模拟 name 重复
o.setName(nameDeptDO.getName()); o.setName(nameDeptDO.getName());
}); });
// 调用, 并断言异常 // 调用, 并断言异常
assertServiceException(() -> deptService.updateDept(reqVO), DEPT_NAME_DUPLICATE); assertServiceException(() -> deptService.updateDept(reqVO), DEPT_NAME_DUPLICATE);
} }
@Test @Test
void testCheckDept_parentNotExitsForCreate() { public void testValidateDept_parentNotExitsForCreate() {
// 准备参数
DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class, DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class,
o -> o.setStatus(randomCommonStatus())); o -> o.setStatus(randomCommonStatus()));
// 调用,并断言异常 // 调用,并断言异常
assertServiceException(() -> deptService.createDept(reqVO), DEPT_PARENT_NOT_EXITS); assertServiceException(() -> deptService.createDept(reqVO), DEPT_PARENT_NOT_EXITS);
} }
@Test @Test
void testCheckDept_notFoundForDelete() { public void testValidateDept_notFoundForDelete() {
// 准备参数 // 准备参数
Long id = randomLongId(); Long id = randomLongId();
// 调用, 并断言异常 // 调用, 并断言异常
assertServiceException(() -> deptService.deleteDept(id), DEPT_NOT_FOUND); assertServiceException(() -> deptService.deleteDept(id), DEPT_NOT_FOUND);
} }
@Test @Test
void testCheckDept_exitsChildrenForDelete() { public void testValidateDept_exitsChildrenForDelete() {
// mock 数据 // mock 数据
DeptDO parentDept = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus())); DeptDO parentDept = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus()));
deptMapper.insert(parentDept);// @Sql: 先插入出一条存在的数据 deptMapper.insert(parentDept);// @Sql: 先插入出一条存在的数据
@ -208,39 +219,39 @@ public class DeptServiceTest extends BaseDbUnitTest {
} }
@Test @Test
void testCheckDept_parentErrorForUpdate() { public void testValidateDept_parentErrorForUpdate() {
// mock 数据 // mock 数据
DeptDO dbDeptDO = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus())); DeptDO dbDeptDO = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus()));
deptMapper.insert(dbDeptDO); deptMapper.insert(dbDeptDO);
// 准备参数 // 准备参数
DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, o -> {
o -> {
// 设置自己为父部门 // 设置自己为父部门
o.setParentId(dbDeptDO.getId()); o.setParentId(dbDeptDO.getId());
// 设置更新的 ID // 设置更新的 ID
o.setId(dbDeptDO.getId()); o.setId(dbDeptDO.getId());
}); });
// 调用, 并断言异常 // 调用, 并断言异常
assertServiceException(() -> deptService.updateDept(reqVO), DEPT_PARENT_ERROR); assertServiceException(() -> deptService.updateDept(reqVO), DEPT_PARENT_ERROR);
} }
@Test @Test
void testCheckDept_notEnableForCreate() { public void testValidateDept_notEnableForCreate() {
// mock 数据 // mock 数据
DeptDO deptDO = randomPojo(DeptDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); DeptDO deptDO = randomPojo(DeptDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()));
deptMapper.insert(deptDO); deptMapper.insert(deptDO);
// 准备参数 // 准备参数
DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class, DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class, o -> {
o -> { // 设置未启用的部门为父部门
// 设置未启用的部门为副部门
o.setParentId(deptDO.getId()); o.setParentId(deptDO.getId());
}); });
// 调用, 并断言异常 // 调用, 并断言异常
assertServiceException(() -> deptService.createDept(reqVO), DEPT_NOT_ENABLE); assertServiceException(() -> deptService.createDept(reqVO), DEPT_NOT_ENABLE);
} }
@Test @Test
void testCheckDept_parentIsChildForUpdate() { public void testCheckDept_parentIsChildForUpdate() {
// mock 数据 // mock 数据
DeptDO parentDept = randomPojo(DeptDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); DeptDO parentDept = randomPojo(DeptDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()));
deptMapper.insert(parentDept); deptMapper.insert(parentDept);
@ -251,18 +262,84 @@ public class DeptServiceTest extends BaseDbUnitTest {
deptMapper.insert(childDept); deptMapper.insert(childDept);
// 初始化本地缓存 // 初始化本地缓存
deptService.initLocalCache(); deptService.initLocalCache();
// 准备参数 // 准备参数
DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, o -> {
o -> {
// 设置自己的子部门为父部门 // 设置自己的子部门为父部门
o.setParentId(childDept.getId()); o.setParentId(childDept.getId());
// 设置更新的 ID // 设置更新的 ID
o.setId(parentDept.getId()); o.setId(parentDept.getId());
}); });
// 调用, 并断言异常 // 调用, 并断言异常
assertServiceException(() -> deptService.updateDept(reqVO), DEPT_PARENT_IS_CHILD); assertServiceException(() -> deptService.updateDept(reqVO), DEPT_PARENT_IS_CHILD);
} }
@Test
public void testGetDeptList() {
// mock 数据
DeptDO deptDO01 = randomDeptDO();
deptMapper.insert(deptDO01);
DeptDO deptDO02 = randomDeptDO();
deptMapper.insert(deptDO02);
// 准备参数
List<Long> ids = Arrays.asList(deptDO01.getId(), deptDO02.getId());
// 调用
List<DeptDO> deptDOList = deptService.getDeptList(ids);
// 断言
assertEquals(2, deptDOList.size());
assertEquals(deptDO01, deptDOList.get(0));
assertEquals(deptDO02, deptDOList.get(1));
}
@Test
public void testGetDept() {
// mock 数据
DeptDO deptDO = randomDeptDO();
deptMapper.insert(deptDO);
// 准备参数
Long id = deptDO.getId();
// 调用
DeptDO dbDept = deptService.getDept(id);
// 断言
assertEquals(deptDO, dbDept);
}
@Test
public void testValidateDeptList_success() {
// mock 数据
DeptDO deptDO = randomDeptDO().setStatus(CommonStatusEnum.ENABLE.getStatus());
deptMapper.insert(deptDO);
// 准备参数
List<Long> ids = singletonList(deptDO.getId());
// 调用无需断言
deptService.validateDeptList(ids);
}
@Test
public void testValidateDeptList_notFound() {
// 准备参数
List<Long> ids = singletonList(randomLongId());
// 调用, 并断言异常
assertServiceException(() -> deptService.validateDeptList(ids), DEPT_NOT_FOUND);
}
@Test
public void testValidateDeptList_notEnable() {
// mock 数据
DeptDO deptDO = randomDeptDO().setStatus(CommonStatusEnum.DISABLE.getStatus());
deptMapper.insert(deptDO);
// 准备参数
List<Long> ids = singletonList(deptDO.getId());
// 调用, 并断言异常
assertServiceException(() -> deptService.validateDeptList(ids), DEPT_NOT_ENABLE);
}
@SafeVarargs @SafeVarargs
private static DeptDO randomDeptDO(Consumer<DeptDO>... consumers) { private static DeptDO randomDeptDO(Consumer<DeptDO>... consumers) {
Consumer<DeptDO> consumer = (o) -> { Consumer<DeptDO> consumer = (o) -> {

View File

@ -509,7 +509,7 @@ public class PermissionServiceTest extends BaseDbUnitTest {
when(userService.getUser(eq(1L))).thenReturn(new AdminUserDO().setDeptId(3L), null, null); // 最后返回 null 的目的看看会不会重复调用 when(userService.getUser(eq(1L))).thenReturn(new AdminUserDO().setDeptId(3L), null, null); // 最后返回 null 的目的看看会不会重复调用
// mock 方法部门 // mock 方法部门
DeptDO deptDO = randomPojo(DeptDO.class); DeptDO deptDO = randomPojo(DeptDO.class);
when(deptService.getDeptsByParentIdFromCache(eq(3L), eq(true))) when(deptService.getDeptListByParentIdFromCache(eq(3L), eq(true)))
.thenReturn(singletonList(deptDO)); .thenReturn(singletonList(deptDO));
// 调用 // 调用

View File

@ -300,7 +300,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
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.getDeptsByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList); when(deptService.getDeptListByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList);
// 调用 // 调用
PageResult<AdminUserDO> pageResult = userService.getUserPage(reqVO); PageResult<AdminUserDO> pageResult = userService.getUserPage(reqVO);
@ -324,7 +324,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
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.getDeptsByParentIdFromCache(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.getUsers(reqVO);
@ -368,7 +368,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
}); });
// mock 方法模拟失败 // mock 方法模拟失败
doThrow(new ServiceException(DEPT_NOT_FOUND)).when(deptService).validDepts(any()); doThrow(new ServiceException(DEPT_NOT_FOUND)).when(deptService).validateDeptList(any());
// 调用 // 调用
UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true); UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true);