I typically find myself struggling when doing some more complex expectations using Prophecy. To make things easier for myself I decided to create this cheatsheet.
$ObjectProphecy->method(
'value'
);
or
$ObjectProphecy->method(
Argument::exact('value')
);
$ObjectProphecy->method(
Argument::is('value')
);
$ObjectProphecy->method(
Argument::type(MyClass::class),
Argument::type('int')
);
$ObjectProphecy->method(
Argument::any()
);
$ObjectProphecy->method(
Argument::cetera() // will pass with any list of parameters, or even without any parameters
);
$ObjectProphecy->method(Argument::allOf(
Argument::containingString('value_1'),
Argument::containingString('value_2')
));
$ObjectProphecy->method(
Argument::not('value'),
Argument::not(Argument::type('array'))
);
$ObjectProphecy->method(
Argument::containingString('value')
);
$ObjectProphecy->method(
Argument::approximate(5, 1)
);
$ObjectProphecy->method(
Argument::size($expectedNumberOfElements)
);
$ObjectProphecy->method(
Argument::containing('value')
);
$ObjectProphecy->method(
Argument::withKey('key')
);
$ObjectProphecy->method(
Argument::withEntry('key', 'value')
);
The argument supplied to Argument::withEveryEntry()
will be matched against every value in the array passed to the prophesized method:
$ObjectProphecy->method(
Argument::withEveryEntry(Argument::type('string'))
);
$ObjectProphecy->method(Argument::allOf(
Argument::withEntry('key_1', 'value_1'),
Argument::withEntry('key_2', 'value_2')
));
Sometimes you might want to make multiple or elaborate checks on arguments.
$ObjectProphecy->method(Argument::that(function(int $param1, string $param2): bool {
// callback function should have the same parameter signature as spied method
// Return `true` to match the argument, `false` if it does not, eg.
return $param1 === $param2;
})
->shouldBeCalled()
->willReturn(/*...*/);
$objectProphecy
->method(Argument::cetera())
->willReturn('a value');
$objectProphecy
->method(Argument::cetera())
->willReturnArgument(0);
$objectProphecy
->method(Argument::cetera())
->will(function(array $args) {
return new Object($args[0]);
});
NB In the callback $this
is bound to the active MethodProphecy
. So in the callback $this
does not refer to the TestCase!