python module_error ai_generated true

属性错误:模块 'unittest' 没有属性 'mock'

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

ID: python/attributeerror-unittest-no-mock

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

版本兼容性

版本状态引入弃用备注
3.2 active
3.3 active
3.4 active

根因分析

在 Python 3.2 及更早版本中,mock 不是 unittest 的一部分;必须单独导入 mock 或在 Python 3.3+ 中使用 unittest.mock。

English

In Python 3.2 and earlier, mock is not part of unittest; must import mock separately or use unittest.mock in Python 3.3+.

generic

解决方案

  1. 95% 成功率 Import mock from unittest for Python 3.3+
    from unittest.mock import Mock, patch
  2. 90% 成功率 Use backport mock for older Python
    pip install mock; then from mock import Mock, patch

无效尝试

常见但无效的做法:

  1. Installing mock via pip 60% 失败

    mock is available as a backport but not integrated into unittest; import path is different.

  2. Using unittest.mock without importing 80% 失败

    If Python version is < 3.3, unittest.mock does not exist.