0PricingLogin
PHP Academy · Lesson

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/mockery

Stub 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

  1. The Test-Driven Development Workflow
  2. Mocking and Stubbing with Mockery
  3. Integration and Functional Testing
  4. Mutation Testing with Infection
← Back to PHP Academy