package email import ( "carrotskin/pkg/config" "sync" "testing" "go.uber.org/zap/zaptest" ) func resetEmail() { serviceInstance = nil once = sync.Once{} } // TestGetService_NotInitialized 测试未初始化时获取邮件服务 func TestGetService_NotInitialized(t *testing.T) { resetEmail() _, err := GetService() if err == nil { t.Error("未初始化时应该返回错误") } expectedError := "邮件服务未初始化,请先调用 email.Init()" if err.Error() != expectedError { t.Errorf("错误消息 = %q, want %q", err.Error(), expectedError) } } // TestMustGetService_Panic 测试MustGetService在未初始化时panic func TestMustGetService_Panic(t *testing.T) { resetEmail() defer func() { if r := recover(); r == nil { t.Error("MustGetService 应该在未初始化时panic") } }() _ = MustGetService() } // TestInit_Email 测试邮件服务初始化 func TestInit_Email(t *testing.T) { resetEmail() cfg := config.EmailConfig{ Enabled: false, SMTPHost: "smtp.example.com", SMTPPort: 587, Username: "user@example.com", Password: "password", FromName: "noreply@example.com", } logger := zaptest.NewLogger(t) err := Init(cfg, logger) if err != nil { t.Errorf("Init() 错误 = %v, want nil", err) } // 验证可以获取服务 service, err := GetService() if err != nil { t.Errorf("GetService() 错误 = %v, want nil", err) } if service == nil { t.Error("GetService() 返回的服务不应为nil") } }