unittest

业务代码
  • services.py
class EmailService:
    """邮件服务(依赖外部SMTP,真实环境中不能随便调用)"""

    def send_welcome_email(self, email: str) -> bool:
        # 假设这里是真实的SMTP发邮件逻辑
        print(f"真实发送邮件到 {email}")
        return True

    def send_reset_password_email(self, email: str, token: str) -> bool:
        print(f"真实发送重置密码邮件到 {email}")
        return True

单元测试代码

  • test_services.py
import unittest
from unittest.mock import Mock, patch

from services import EmailService


class TestServices(unittest.TestCase):
    @patch('services.EmailService.send_welcome_email')
    def test_send_welcome_email(self, email_mock: Mock):
        # 配置 Mock
        email_mock.return_value = False

        # 调用真实方法
        user_service = EmailService()
        result = user_service.send_welcome_email('[email protected]')
        # ✅ result 现在是 False
        print(f"result: {result}")  # result: False
        self.assertFalse(result)

        # 验证 Mock 被正确调用
        email_mock.assert_called_once_with('[email protected]')

if __name__ == '__main__':
    unittest.main()
测试套件
  • test_suite.py
import unittest

from test_services import TestServices

test_suite = unittest.TestSuite()
test_suite.addTest(TestServices())
if __name__ == '__main__':
    unittest.main()
posted @ 2026-05-09 16:46  gz_xiaohai  阅读(3)  评论(0)    收藏  举报