package com.label.unit; import com.label.common.exception.BusinessException; import com.label.entity.SysCompany; import com.label.mapper.SysCompanyMapper; import com.label.mapper.SysUserMapper; import com.label.service.CompanyService; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @DisplayName("公司管理服务测试") class CompanyServiceTest { private final SysCompanyMapper companyMapper = mock(SysCompanyMapper.class); private final SysUserMapper userMapper = mock(SysUserMapper.class); private final CompanyService companyService = new CompanyService(companyMapper, userMapper); @Test @DisplayName("创建公司时写入 ACTIVE 状态并保存公司代码") void createCompanyInsertsActiveCompany() { SysCompany company = companyService.create("测试公司", "TEST"); assertThat(company.getCompanyName()).isEqualTo("测试公司"); assertThat(company.getCompanyCode()).isEqualTo("TEST"); assertThat(company.getStatus()).isEqualTo("ACTIVE"); verify(companyMapper).insert(any(SysCompany.class)); } @Test @DisplayName("创建公司时拒绝重复公司代码") void createCompanyRejectsDuplicateCode() { SysCompany existing = new SysCompany(); existing.setId(1L); when(companyMapper.selectByCompanyCode("DEMO")).thenReturn(existing); assertThatThrownBy(() -> companyService.create("演示公司", "DEMO")) .isInstanceOf(BusinessException.class) .hasMessageContaining("公司代码已存在"); } @Test @DisplayName("禁用公司时只允许 ACTIVE 或 DISABLED") void updateStatusRejectsInvalidStatus() { SysCompany existing = new SysCompany(); existing.setId(1L); existing.setStatus("ACTIVE"); when(companyMapper.selectById(1L)).thenReturn(existing); assertThatThrownBy(() -> companyService.updateStatus(1L, "DELETED")) .isInstanceOf(BusinessException.class) .hasMessageContaining("公司状态不合法"); } @Test @DisplayName("删除公司时若仍有关联用户则拒绝删除") void deleteRejectsCompanyWithUsers() { SysCompany existing = new SysCompany(); existing.setId(1L); when(companyMapper.selectById(1L)).thenReturn(existing); when(userMapper.countByCompanyId(1L)).thenReturn(2L); assertThatThrownBy(() -> companyService.delete(1L)) .isInstanceOf(BusinessException.class) .hasMessageContaining("公司下仍存在用户"); } }