mock-count

A test makes or stubs more test doubles than one or two.

Group
Tests
Runs
On by default
Level
note
Reads
Tests
Fix
None: which collaborators can be real is the author's to say
Defends
Resilience: the test fails only when the code is broken.

Why

The test makes more than two test doubles, or tells one double how more than two of its methods behave. The post gives both signs of overusing mocks: such a test knows the code's collaborators rather than its behavior, and must change whenever the implementation does.

The fix, as Ur suggests it: use the real collaborator or a fake in place of some of the doubles.

For agents

Make at most two test doubles in a test and stub at most two methods of each; past that, use the real collaborator or a fake.

Example

shop/checkout.py
def checkout(cart, payments, receipts, stock):
    stock.reserve(cart.items)
    charge = payments.charge(cart.total)
    receipts.send(cart.owner, charge.reference, cart.total)
    return charge.reference
tests/test_checkout.py
from unittest.mock import Mock

from shop.checkout import checkout


def test_checkout_charges_the_cart():
    cart = Mock()
    payments = Mock()
    receipts = Mock()
    stock = Mock()
    checkout(cart, payments, receipts, stock)
    payments.charge.assert_called_once_with(cart.total)
What Ur prints
$ ur lint --rule mock-count
note[mock-count]: test `test_checkout_charges_the_cart` makes 4 test doubles; more than 2 is a sign the test knows the code's collaborators rather than its behavior
  --> ./tests/test_checkout.py:9:16 test `test_checkout_charges_the_cart`
  = step 1: ./tests/test_checkout.py:7:12 makes a double
  = step 2: ./tests/test_checkout.py:8:16 makes a double
  = step 3: ./tests/test_checkout.py:9:16 makes a double
  = step 4: ./tests/test_checkout.py:10:13 makes a double
  = hint: use the real collaborator or a fake in place of some of the doubles
  = see: Testing on the Toilet: Don't Overuse Mocks, Google Testing Blog (2013-05-28), https://testing.googleblog.com/2013/05/testing-on-toilet-dont-overuse-mocks.html
0 clone classes and 1 test finding in 2 files

Try it in the playground →

Source

Testing on the Toilet: Don't Overuse Mocks, Google Testing Blog (2013-05-28).