Skip to content

no-mocked-pydantic-value-object

Build real Pydantic models when test doubles supply model field data.

Why

Mocking a Pydantic value object bypasses validation, defaults, serialization, and field relationships. A specced mock still permits test data that the real model could never produce. Real model fixtures keep those contracts active while allowing services and external boundaries to remain mocked.

Fix

Construct the real model, using a small typed factory for repeated valid defaults. Keep mock behavior at collaborator boundaries; a model method deliberately configured to raise remains a valid failure-injection test.

Examples

Before — flagged A mock bypasses the model's validated data contract
tests/test_profile.py
from unittest.mock import Mock
from pydantic import BaseModel
class Profile(BaseModel):
language: str
def test_profile():
profile = Mock(spec=Profile)
profile.language = "ar"
After — preferred Real model fixtures retain validation and defaults
tests/test_profile.py
from pydantic import BaseModel
class Profile(BaseModel):
language: str
def make_profile(*, language: str = "en") -> Profile:
return Profile(language=language)
def test_profile():
profile = make_profile(language="ar")
assert profile.language == "ar"