python module_error ai_generated true

AttributeError: 模块 'unittest' 没有属性 'mock'

AttributeError: module 'unittest' has no attribute 'mock'

ID: python/unittest-mock-no-attribute

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-01-22首次发现

版本兼容性

版本状态引入弃用备注
3.9 active — — —
3.11 active — — —
3.12 active — — —

根因分析

`unittest.mock` 是子模块,必须显式导入。仅写 `import unittest` 后使用 `unittest.mock.patch(...)` 会失败,因为子模块未被加载。

English

`unittest.mock` is a submodule that must be imported explicitly. Writing `import unittest` then `unittest.mock.patch(...)` fails because the submodule isn't loaded until imported.

generic

解决方案

  1. 98% 成功率
    Import the submodule explicitly:
    from unittest import mock
    # or
    import unittest.mock
    
    with mock.patch('mymodule.requests.get') as m:
        ...

无效尝试

常见但无效的做法:

  1. 80% 失败

    mock has been a submodule since 3.3; version is not the problem, import style is.

  2. 65% 失败

    Installing the backport doesn't bind `unittest.mock`; the attribute error persists.