📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHPUnit Testing Test Doubles — Spies

Test Doubles — Spies

5 min read
Verify call counts with expects($this->once/exactly/never) — turn mocks into spies.

Spies with Mock Objects

class OrderServiceTest extends TestCase {
    public function testNotificationSentOnce(): void {
        $notifier = $this->createMock(NotificationService::class);

        // Verify method is called exactly once
        $notifier->expects($this->once())->method("send");

        // Verify never called
        $notifier->expects($this->never())->method("sendBulk");

        // Verify called exactly N times
        $notifier->expects($this->exactly(3))->method("log");

        // Verify called with specific arguments
        $notifier->expects($this->once())
                 ->method("send")
                 ->with(
                     $this->equalTo("Order shipped"),
                     $this->stringContains("tracking"),
                 );

        (new OrderService($notifier))->ship($order);
    }
}