Skip to content

Cheat sheet

Creating Mocks

Mocking a simple class

$mock = Phake::mock(MyClassToMock::class);

Mocking an interface

$mock = Phake::mock(MyInterface::class);

Mocking multiple interfaces

$mock = Phake::mock([ MyInterface1::class, MyInterface2::class ]);

Create a partial Mock

$mock = Phake::partialMock(MyClassToMock::class, ...$constructorParams);

Method stubbing

Stubbing a simple call to the calledMethod()

$mock = Phake::mock(MyClassToMock::class);
Phake::when($mock)->calledMethod('someParameter')->thenReturn('My return value');

Stubbing multiple calls to calledMethod() with different parameters

$mock = Phake::mock(MyClassToMock::class);
Phake::when($mock)->calledMethod('someParameter')->thenReturn('My return value');
Phake::when($mock)->calledMethod('someOtherParameter')->thenReturn('My other return value');

Stub calls to calledMethod() regardless of parameters.

$mock = Phake::mock(MyClassToMock::class);
Phake::when($mock)->calledMethod(Phake::anyParameters())->thenReturn($result);

// or the shorter version

Phake::when($mock)->calledMethod->thenReturn($result);

Stub call to calledMethod() using callback

$mock = Phake::mock(MyClassToMock::class);
Phake::when($mock)->calledMethod($param1)->thenReturnCallback(fn($x) => $x + 1);

Stub consecutive calls to calledMethod()

$mock = Phake::mock(MyClassToMock::class);
Phake::when($mock)->calledMethod()->thenReturn(10)->thenReturn(20)->thenReturn(30);

Throw an exception when calledMethod() is called

$mock = Phake::mock(MyClassToMock::class);
Phake::when($mock)->calledMethod()->thenThrow(new \Exception('Some exception'));

Method Verifications (Spies)

Verify that the calledMethod() was called once without parameters

Phake::verify($mock)->calledMethod();

Verify that the calledMethod() was called once with a specific parameter

Phake::verify($mock)->calledMethod('param');

Verify that the calledMethod() was called twice without parameters

Phake::verify($mock, Phake::times(2))->calledMethod();

Verify that the calledMethod() was called at least twice without parameters

Phake::verify($mock, Phake::atLeast(2))->calledMethod();

Verify that the calledMethod() was called at most twice without parameters

Phake::verify($mock, Phake::atMost(2))->calledMethod();

Verify that the calledMethod() was never called without parameters

Phake::verify($mock, Phake::never())->calledMethod();

Verify that mock did not receive any interaction

Phake::verifyNoInteraction($mock);

Verify that calls were made in order

Phake::inOrder(
    Phake::verify($mock)->firstCall(),
    Phake::verify($mock2)->secondCall(),
    Phake::verify($mock)->yetAnOthercall()
);

Capture parameters

Phake::verify($mock)->calledMethod(Phake::capture($parameter1));