Skip to content

Python · testing

over-mocked-test

python:over-mocked-test

Tests should not replace more than five distinct collaborators.

Code
SARJ062
Default
error
Fix
none
Languages
python

Why

Broad mock wiring couples tests to implementation details while exercising little production behavior.

Fix

Use real dependencies or a higher-level test harness and mock only true external boundaries.

Before / after

Executed by this rule’s unit tests.

Before

Test patches six collaborators

tests/test_service.py · focus
from unittest.mock import patch

@patch("app.mod0.collaborator")
@patch("app.mod1.collaborator")
@patch("app.mod2.collaborator")
@patch("app.mod3.collaborator")
@patch("app.mod4.collaborator")
@patch("app.mod5.collaborator")
def test_run(a, b, c, d, e, f):
    assert run() == 1

After

Test patches one external boundary

tests/test_service.py · focus
from unittest.mock import patch

@patch("app.payment_gateway")
def test_run(gateway):
    assert run() == 1

Limits

  • Only collected tests are analyzed; configuration knobs do not count as collaborators.