test: 添加邮件服务测试类

- 新增EmailServiceTest测试类
- 测试验证码发送功能
- 测试连续发送验证码覆盖逻辑
- 新增application-test.yml测试配置

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-01-09 23:57:42 +08:00
parent 7aacad2596
commit dfcb7d978b
2 changed files with 112 additions and 0 deletions

View File

@@ -0,0 +1,86 @@
package cn.meowrain.aioj.backend.userservice.service;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.ActiveProfiles;
import static org.junit.jupiter.api.Assertions.*;
/**
* 邮件服务测试类
*/
@Slf4j
@SpringBootTest
@ActiveProfiles("test")
class EmailServiceTest {
@Autowired
private EmailService emailService;
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 测试发送验证码邮件
* 注意:运行此测试前,请将下面的邮箱地址替换为你自己的邮箱
*/
@Test
void testSendVerifyCode() {
// TODO: 替换成你的真实邮箱地址
String testEmail = "meowrain@126.com";
log.info("开始发送验证码到邮箱: {}", testEmail);
// 发送验证码
assertDoesNotThrow(() -> emailService.sendVerifyCode(testEmail));
log.info("验证码邮件发送成功,请检查邮箱(含垃圾邮件文件夹)");
// 验证 Redis 中是否存储了验证码
String redisKey = "email:code:" + testEmail;
String code = redisTemplate.opsForValue().get(redisKey);
assertNotNull(code, "验证码应该存储在 Redis 中");
log.info("Redis 中存储的验证码: {}", code);
// 提示用户
log.info("===============================================");
log.info("请登录邮箱查看验证码: {}", testEmail);
log.info("验证码: {}", code);
log.info("===============================================");
}
/**
* 测试连续发送验证码(应该覆盖之前的验证码)
*/
@Test
void testSendMultipleCodes() {
String testEmail = "your-email@qq.com";
log.info("测试连续发送两次验证码");
// 第一次发送
emailService.sendVerifyCode(testEmail);
String firstCode = redisTemplate.opsForValue().get("email:code:" + testEmail);
log.info("第一次验证码: {}", firstCode);
// 等待 1 秒
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
// 第二次发送
emailService.sendVerifyCode(testEmail);
String secondCode = redisTemplate.opsForValue().get("email:code:" + testEmail);
log.info("第二次验证码: {}", secondCode);
assertNotNull(secondCode, "第二次发送后应该有新的验证码");
}
}

View File

@@ -0,0 +1,26 @@
spring:
mail:
host: smtp.qq.com
port: 465
username: 2705356115@qq.com
password: yohcndfrlxwcdfed
default-encoding: UTF-8
protocol: smtp
properties:
mail:
smtp:
ssl:
enable: true
auth: true
starttls:
enable: true
data:
redis:
host: 10.0.0.10
port: 6379
password: 123456
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://10.0.0.10/aioj_dev
username: root
password: root