python
module_error
ai_generated
true
ImportError: 没有名为 'module_to_patch' 的模块
ImportError: No module named 'module_to_patch'
ID: python/unittest-mock-patch-import-error
80%修复率
85%置信度
0证据数
2025-07-25首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
`@unittest.mock.patch('module_to_patch.ClassName')` 装饰器尝试修补一个不存在或不可导入的模块。
English
The `@unittest.mock.patch('module_to_patch.ClassName')` decorator tries to patch a module that does not exist or is not importable.
解决方案
-
95% 成功率
Ensure the module path is correct: `@patch('my_package.module_to_patch.ClassName')` -
90% 成功率
Use patch.object() with the actual class: `@patch.object(MyClass, 'method_name')`
无效尝试
常见但无效的做法:
-
60% 失败
The module might be an internal part of the codebase that should be patched differently.
-
90% 失败
Decorators are evaluated at import time; try-except cannot catch import errors in this context.