Mocking Dependencies with PHPUnit
Create mock objects to isolate units and control collaborator behavior.
Mocking Dependencies with PHPUnit is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Mock?
Mocking replaces a real dependency (database, email service, HTTP client) with a controllable fake so tests are fast, isolated, and deterministic.
createMock()
createMock(ClassName::class) creates a mock object that implements all methods of the class, returning null by default.
<?php
$mailer = $this->createMock(Mailer::class);
// All methods return null by defaultExpecting Method Calls
Use expects() with matchers like once(), exactly(3), never(), any() to verify that methods are called the right number of times.
<?php
$mailer->expects($this->once())
->method("send")
->with("user@example.com", "Welcome!");Stubbing Return Values
Use willReturn() to make a mock method return a specific value.
<?php
$repo = $this->createMock(UserRepository::class);
$repo->method("find")
->willReturn(new User(id: 1, name: "Alice"));willReturnMap()
Return different values depending on the argument using willReturnMap().
<?php
$cache->method("get")
->willReturnMap([
["key:1", "value-one"],
["key:2", "value-two"],
]);willThrowException()
Make a mock throw an exception to test error handling paths.
<?php
$repo->method("find")
->willThrowException(new DatabaseException("Connection lost"));Argument Matchers
Use argument matchers in with() for flexible assertions: $this->anything(), $this->equalTo(), $this->isInstanceOf().
<?php
$logger->expects($this->once())
->method("log")
->with($this->stringContains("error"));Partial Mocks (getMockBuilder)
Use getMockBuilder() with onlyMethods() to mock specific methods while keeping real implementations for others.
<?php
$svc = $this->getMockBuilder(EmailService::class)
->onlyMethods(["sendRaw"])
->getMock();
$svc->method("sendRaw")->willReturn(true);Spy Pattern
A spy records all calls so you can assert on them after execution — PHPUnit mocks can act as spies by using any() and capturing arguments.
Injecting Mocks
Pass mocks into the class under test via constructor injection — the standard pattern for testable, decoupled code.
<?php
$service = new NotificationService($mailer, $logger);
$service->notify($user);Interface vs Concrete Class Mocks
Mocking interfaces is preferred — no implementation details bleed into the test, and tests remain valid even if the real implementation changes.
Summary
Use createMock() to isolate dependencies. Use expects()->method()->with()->willReturn() to set expectations and stubs. Inject mocks via constructor.
Quick Check
Which method makes a mock return a specific value?
Frequently asked questions
Is the “Mocking Dependencies with PHPUnit” lesson free?
Yes — the full text of “Mocking Dependencies with PHPUnit” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Mocking Dependencies with PHPUnit”?
Create mock objects to isolate units and control collaborator behavior. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Mocking Dependencies with PHPUnit” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- PHPUnit Setup and First Test
- Assertions and Test Methods
- Data Providers for Parameterized Tests
- Mocking Dependencies with PHPUnit