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

Stubs

6 min read Quiz at the end
Use createStub() to return canned values without verifying call expectations — simpler than mocks.

Stubs

// Stubs return canned responses without expectations
class PaymentTest extends TestCase {
    public function testProcessPaymentSuccess(): void {
        // Stub — we control what it returns, no expectations
        $gateway = $this->createStub(PaymentGateway::class);
        $gateway->method("charge")->willReturn(["status" => "success"]);

        $service = new PaymentService($gateway);
        $result  = $service->process(100.00);

        $this->assertEquals("success", $result["status"]);
    }

    public function testProcessPaymentFailure(): void {
        $gateway = $this->createStub(PaymentGateway::class);
        $gateway->method("charge")->willReturn(["status" => "failed"]);

        $service = new PaymentService($gateway);

        $this->expectException(PaymentFailedException::class);
        $service->process(100.00);
    }

    // Stub throwing exceptions
    public function testGatewayError(): void {
        $gateway = $this->createStub(PaymentGateway::class);
        $gateway->method("charge")->willThrowException(new GatewayException("Timeout"));

        $this->expectException(GatewayException::class);
        (new PaymentService($gateway))->process(50.00);
    }
}
Topic Quiz · 2 questions

Test your understanding before moving on

1. Which method creates a stub?
💡 $this->createStub() creates a test double with no expectation checking.
2. When should you use a Stub vs Mock?
💡 Stub for return values only; Mock when you need to verify the call happened.