返回专栏
专栏 ·

8.3 自动化测试体系:pytest 核心用法、Fixture 依赖注入与 Mock 单元测试实战

作者: 九路 共 12 章 · 48 小节

欢迎回到 HelloWorld 技术社区(www.helloworld.net) 《Python 现代开发实战》专栏。

没有自动化测试的重构就是“蒙眼走钢丝”。现代 Python 测试界毫无争议的王者是 pytest——无需继承繁琐的 TestCase 类,直接用原生 assert 断言即可,失败时它会自动展开对比变量的详细差异。

from unittest.mock import MagicMock
import pytest


class NotificationService:
    def __init__(self, sms_client: object) -> None:
        self.sms_client = sms_client

    def notify_login(self, phone: str) -> bool:
        if not phone.startswith("1") or len(phone) != 11:
            raise ValueError("非法手机号格式")
        return self.sms_client.send(phone, "您已成功登录 HelloWorld 社区")


# 1. 使用 Fixture 注入依赖(可自动管理测试前置准备与后置清理)
@pytest.fixture
def service() -> NotificationService:
    mock_client = MagicMock()
    mock_client.send.return_value = True  # 隔离外部真实短信网关,零成本秒级测试
    return NotificationService(sms_client=mock_client)


# 2. 参数化测试:一套逻辑覆盖多组边界输入
@pytest.mark.parametrize("bad_phone", ["12345", "23800138000", ""])
def test_notify_invalid_phone(service: NotificationService, bad_phone: str) -> None:
    with pytest.raises(ValueError, match="非法手机号"):
        service.notify_login(bad_phone)


def test_notify_success(service: NotificationService) -> None:
    assert service.notify_login("13800138000") is True
    service.sms_client.send.assert_called_once()

💬 HelloWorld 社区实战打卡

为什么在单元测试中必须使用 Mock 隔离第三方支付、短信和外部 HTTP 接口?带 #Python专栏打卡 聊聊你的看法!