package com.tcm.training.admin.app.auth.service; import com.tcm.training.admin.app.auth.config.AppAliyunSmsProperties; import com.tcm.training.admin.utils.MsgUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; /** * APP 阿里云短信发送实现测试。 */ @ExtendWith(MockitoExtension.class) class AliyunAppSmsSenderTest { @Mock private MsgUtils msgUtils; @Captor private ArgumentCaptor> paramsCaptor; private AppAliyunSmsProperties properties; private AliyunAppSmsSender aliyunAppSmsSender; /** * 每个用例前构造阿里云短信发送器。 */ @BeforeEach void setUp() { properties = new AppAliyunSmsProperties(); properties.setAccessKeyId("test-ak"); properties.setAccessKeySecret("test-sk"); properties.setSignName("海诊通"); properties.getTemplates().setLogin("SMS_505135234"); properties.getTemplates().setRegister("SMS_505065330"); properties.getTemplates().setPasswordReset("SMS_505095303"); properties.getTemplates().setPhoneChange("SMS_505135235"); aliyunAppSmsSender = new AliyunAppSmsSender(msgUtils, properties); } /** * 登录验证码应使用登录模板并透传 code 参数。 */ @Test void sendLoginCodeShouldUseLoginTemplate() throws Exception { doNothing().when(msgUtils).sendMsg(eq("13800138000"), paramsCaptor.capture(), eq("SMS_505135234"), eq("海诊通")); aliyunAppSmsSender.sendLoginCode("13800138000", "666666"); assertEquals("666666", paramsCaptor.getValue().get("code")); } /** * 短信发送失败时应向上抛出统一业务异常。 */ @Test void sendRegisterCodeShouldThrowWhenMsgUtilsFails() throws Exception { doThrow(new IllegalStateException("短信发送失败,请稍后重试")) .when(msgUtils).sendMsg(eq("13800138001"), org.mockito.ArgumentMatchers.anyMap(), eq("SMS_505065330"), eq("海诊通")); IllegalStateException exception = assertThrows(IllegalStateException.class, () -> aliyunAppSmsSender.sendRegisterCode("13800138001", "123456")); assertEquals("短信发送失败,请稍后重试", exception.getMessage()); } /** * 模板配置不完整时应直接拒绝发送。 */ @Test void sendPhoneChangeCodeShouldFailWhenTemplateMissing() { properties.getTemplates().setPhoneChange(""); IllegalStateException exception = assertThrows(IllegalStateException.class, () -> aliyunAppSmsSender.sendPhoneChangeCode("13800138002", "123456")); assertEquals("短信发送配置不完整", exception.getMessage()); } }