python type_error ai_generated true

AttributeError: Mock 对象没有属性 'fetch_user'

AttributeError: Mock object has no attribute 'fetch_user'

ID: python/unittest-mock-autospec-missing

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

版本兼容性

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

根因分析

使用了普通 MagicMock 而非 create_autospec,方法名拼写错误被静默接受,直到 mock 被当作真实对象使用并查找属性时才暴露。

English

A plain MagicMock was used instead of create_autospec, so typos in method names are silently accepted until the mock is used as the real object and the attribute is looked up.

generic

解决方案

  1. 95% 成功率
    from unittest.mock import create_autospec
    mock_svc = create_autospec(UserService, instance=True)
    # mock_svc.fetch_user now exists and typo'd names raise AttributeError
  2. 90% 成功率
    from unittest.mock import Mock
    mock_svc = Mock(spec=UserService)

无效尝试

常见但无效的做法:

  1. 70% 失败

    Fixes one symptom but the mock still accepts any typo, so the next misspelling fails the same way.

  2. 75% 失败

    Loses the ability to assert calls and may trigger real I/O or DB access.