Mock Objects
6 min read Quiz at the end
Create mock objects, set call expectations with expects(), and control return values with willReturn().
Mock Objects
// Mocking dependencies
class EmailService {
public function send(string $to, string $subject): bool { /* real implementation */ }
}
class UserService {
public function __construct(private EmailService $email) {}
public function register(string $email): bool {
// ... create user ...
return $this->email->send($email, "Welcome!");
}
}
class UserServiceTest extends TestCase {
public function testRegisterSendsEmail(): void {
// Create mock
$emailMock = $this->createMock(EmailService::class);
// Set expectation
$emailMock->expects($this->once())
->method("send")
->with("alice@example.com", "Welcome!")
->willReturn(true);
$service = new UserService($emailMock);
$result = $service->register("alice@example.com");
$this->assertTrue($result);
}
}
Topic Quiz · 4 questions
Test your understanding before moving on
1. What is a Mock object?
💡 A Mock sets expectations on method calls — test fails if expectations not met.
2. What is the difference between a Mock and a Stub?
💡 Stubs provide canned answers; Mocks also verify how collaborators were called.
3. Which method creates a mock in PHPUnit?
💡 $this->createMock(ClassName::class) creates a mock object.
4. What does expects($this->once()) assert?
💡 expects($this->once()) fails the test if method not called exactly once.