Mock Plugin


The Mock Plugin for Pest adds mocking capabilities to Pest - it's a very simple API built on top of Mockery.

In unit tests, mock objects simulate the behaviour of real objects. They are commonly utilised to offer test isolation, to stand in for objects which do not yet exist, or to allow for the exploratory design of class APIs without requiring actual implementation up front.

Source code:


NOTE: This plugin requires PHP 8 or later due to the use of named parameters.

Install the Mock Plugin via the Composer package manager:

1composer require pestphp/pest-plugin-mock --dev

Available functions


The mock() function allows you to declare methods call expectations:

1test('some service', function () {
2 $mock = mock(UserRepository::class)->expect(
3 create: fn ($name) => false,
4 save: fn ($name) => true,
5 );
7 expect($mock->create('Nuno'))->toBeFalse();
8 expect($mock->save('Nuno'))->toBeTrue();

When using the expect(callable ...$methods) method, you will be creating an expectation that each given method should be called at least once and return the given callable result.

Of course, while the expect(callable ...$methods) method addresses most of the traditional mocking needs, you may have more complex cases that require to use the underlying Mockery mock instance:

1test('some service', function () {
2 $mock = mock(UserRepository::class)
3 ->shouldReceive('save')
4 ->andReturn(true)
5 ->getMock();
7 expect($mock->save('Nuno'))->toBeTrue();

For the full list of available methods, please refer to the Mockery documentation.

Next section: Money Plugin →