python type_error ai_generated true

AttributeError: Mock object has no attribute 'some_method'

ID: python/attributeerror-mock-object-has-no-attribute

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-10-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.9 active
3.10 active

Root Cause

A mock object is created without specifying the attribute, and the code tries to access an undefined attribute.

generic

中文

创建模拟对象时未指定属性,代码尝试访问未定义的属性。

Workarounds

  1. 95% success Configure mock with spec or autospec
    mock = Mock(spec=MyClass); mock.some_method.return_value = 42
  2. 90% success Set attribute directly on mock
    mock = Mock(); mock.some_method = MagicMock(return_value=42)

Dead Ends

Common approaches that don't work:

  1. Adding attribute via mock.attach_mock 60% fail

    attach_mock is for attaching additional mocks, not simple attributes.

  2. Using mock.reset_mock() 80% fail

    Reset clears call history but does not add missing attributes.