Mocking and Stubbing with Mockery
Isolate units with flexible test doubles.
Why a Dedicated Mocking Library
PHPUnit ships its own test-double API, but Mockery offers a more fluent, expressive syntax and capabilities PHPUnit's mocks lack — partial mocks, spies, flexible argument matching, and ordered expectations. For complex collaboration-heavy code, Mockery often reads far better. This lesson covers the full spectrum of doubles and when to use each.
composer require --dev mockery/mockeryStub vs Mock vs Spy
Precise vocabulary prevents confused tests:
- Stub — returns canned values; you assert on state (the result).
- Mock — has expectations on calls; you assert on behavior (it was called correctly). Failing expectations fail the test.
- Spy — records calls and lets you assert after the fact.
Rule of thumb: prefer stubs for queries, mocks/spies for commands.
All lessons in this course
- The Test-Driven Development Workflow
- Mocking and Stubbing with Mockery
- Integration and Functional Testing
- Mutation Testing with Infection