Back to results for “Dependency Injection”
PHP › Unit Testing with PHPUnit

What are mock objects in PHPUnit, and why are they useful when testing a piece of code that depends on an external service, such as sending an email or calling a third party API?

Intermediate

Answer

A mock object is a fake, controlled substitute for a real dependency, created specifically for use within a test, and using a mock instead of the actual real dependency lets you test a piece of code in complete isolation without needing to genuinely send a real email, make an actual external API call, or hit a real database, while also letting you precisely control exactly what that fake dependency returns and verify exactly how many times and with what specific arguments it was actually called, which makes tests significantly faster, more reliable, and fully repeatable regardless of the availability of any real external service.
public function testOrderConfirmationEmailIsSent(): void
{
    $mailer = $this->createMock(MailerInterface::class);
    $mailer->expects($this->once())->method('send');

    $orderService = new OrderService($mailer);
    $orderService->confirmOrder($order);
}
Real-world example A test verifying that placing an order triggers a confirmation email uses a mock mailer object instead of an actual real mailer, confirming the send method was called exactly once without ever genuinely sending a real email during the test run.

Common follow-ups: What is the difference between a mock, a stub, and a fake in testing terminology?;How do you configure a mock object to return a specific, predetermined value when one of its methods is called?