SyntaxStudy
Sign Up
PHP Mocking with PHPUnit
PHP Intermediate 4 min read

Mocking with PHPUnit

Mocking

Mocks replace real dependencies with controlled fakes. PHPUnit's createMock() generates an implementation from an interface or class.

Example
class OrderServiceTest extends TestCase {
    public function test_sends_confirmation_email(): void {
        $mailer = $this->createMock(Mailer::class);
        $mailer->expects($this->once())
               ->method("send")
               ->with($this->equalTo("user@example.com"));
        $service = new OrderService($mailer);
        $service->place(new Order(["email" => "user@example.com"]));
    }
}
Pro Tip

Inject dependencies via constructor to make classes mockable — avoid static calls in testable code.