python type_error ai_generated true

AttributeError: Mock object has no attribute 'foo' when using spec=MyClass

ID: python/unittest-mock-spec-attribute

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2025-10-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active

Root Cause

Creating a mock with spec=MyClass restricts the mock to only have attributes that exist on MyClass, and accessing a non-existent attribute raises an AttributeError.

generic

中文

使用 spec=MyClass 创建模拟对象会限制模拟仅具有 MyClass 上存在的属性,访问不存在的属性会引发 AttributeError。

Workarounds

  1. 80% success
    Add the missing attribute to MyClass or use a mock with spec=MyClass and then add the attribute dynamically: mock.foo = MagicMock()
  2. 85% success
    Use autospec=True instead of spec to automatically create a mock that matches the class's interface.

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Using spec_set=True instead of spec still raises the same error for non-existent attributes.

  2. 60% fail

    Removing the spec parameter entirely allows any attribute but may hide API mismatches.