首页/开发/软件测试速查/pytest-mock 的 mocker 夹具
自动化测试66 条

pytest-mock 的 mocker 夹具

pytest-mock 提供 mocker 夹具封装 patch/spy,随用例自动清理;相比手写 unittest.mock 上下文样板更少,且能与 fixture 系统组合。

软件测试速查开发更新于 2026-10-12

补丁与间谍

补丁与间谍
def test_submit(mocker):
    send = mocker.patch("app.mailer.send", return_value=True)
    order.submit()
    send.assert_called_once()


def test_spy(mocker):
    spy = mocker.spy(cart, "total")
    cart.checkout()
    spy.assert_called()
替换范围尽量止步于依赖模块,不要深入到被测对象的内部实现,避免断言绑定实现细节。

易错点

  • patch 目标写错:from x import y 之后应 patch 使用方模块里的名字
  • 对私有方法大量打桩,重构即失败,用例维护成本上升

数据来源与参考

  • pytest-mock 官方文档(pytest-mock.readthedocs.io)
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌