mock-returns-mock

A test double returns another test double.

Group
Tests
Runs
On by default
Level
warning
Reads
Tests
Fix
None: what the middle collaborator should be is the author's to say
Defends
Fidelity: when the code is broken, the test fails.

Why

The test tells a double to return a double it made, so the test walks the code's collaborators one mock at a time and checks nothing any of them does.

The fix, as Ur suggests it: return a real value, or replace the chain with a fake.

For agents

Never make a test double return another test double; use a real object or a fake for the one in the middle.

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
from shop.basket import Cart, Stock


def test_checkout_returns_the_charge_reference():
    payments = Mock()
    charge = Mock()
    payments.charge.return_value = charge
    reference = checkout(Cart("ada", 24), payments, Mock(), Stock())
    assert reference == charge.reference
What Ur prints
$ ur lint --rule mock-returns-mock
warning[mock-returns-mock]: a test double in test `test_checkout_returns_the_charge_reference` returns another double, so the test walks the code's collaborators one mock at a time
  --> ./tests/test_checkout.py:10:5 test `test_checkout_returns_the_charge_reference`
  = hint: return a real value, or replace the chain with a fake
  = see: My Unified Theory of Bugs, Google Testing Blog (2008-11-18), https://testing.googleblog.com/2008/11/my-unified-theory-of-bugs.html
0 clone classes and 1 test finding in 2 files

Try it in the playground →

Source

My Unified Theory of Bugs, Google Testing Blog (2008-11-18).