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

Mockery

5 min read
Use Mockery for fluent expressive mocking with shouldReceive, argument matchers, and andReturn.

Mockery — Advanced Mocking

composer require --dev mockery/mockery

use Mockery;
use MockeryMockInterface;
use PHPUnitFrameworkTestCase;

class UserServiceTest extends TestCase {
    public function testSendWelcomeEmail(): void {
        // Mockery mock
        $mailer = Mockery::mock(Mailer::class);
        $mailer->shouldReceive("send")
               ->once()
               ->with("alice@example.com", Mockery::type("string"))
               ->andReturn(true);

        // Partial mock (spy only some methods)
        $service = Mockery::mock(UserService::class)->makePartial();
        $service->shouldReceive("validateEmail")->andReturn(true);

        (new UserService($mailer))->register("alice@example.com");

        Mockery::close(); // verify all expectations
    }

    protected function tearDown(): void {
        Mockery::close();
        parent::tearDown();
    }
}