Callable Fake is a PHP testing utility by Tim Macdonald that “allows you to fake, capture, and assert against invocations of a callable / Closure.” In some cases, this package can assist in testing scenarios where you allow a developer to pass a callable.
It has a Laravel fake-inspired API that looks something like this:
// Before, you might collect callables to assert later...
public function testEachLoopsOverAllDependencies(): void
{
// arrange
$received = [];
$expected = factory(Dependency::class)->times(2)->create();
$repo = $this->app[DependencyRepository::class];
// act
$repo->each(function (Dependency $dependency) use (&$received): void {
$received[] = $dependency;
});
// assert
$this->assertCount(2, $received);
$this->assertTrue($expected[0]->is($received[0]));
$this->assertTrue($expected[1]->is($received[1]));
}
Using this package you can use something like the following instead:
public function testEachLoopsOverAllDependencies(): void
{
// arrange
$callable = new CallableFake();
$expected = factory(Dependency::class)->times(2)->create();
$repo = $this->app[DependencyRepository::class];
// act
$repo->each($callable);
// assert
$callable->assertTimesInvoked(2);
$callable->assertCalled(function (Depedency $dependency) use ($expected): bool {
return $dependency->is($expected[0]);
});
$callable->assertCalled(function (Dependency $dependency) use ($expected): bool {
return $dependency->is($expected[1]);
});
}
This package provides assertions like assertCalled
, assertNotCalled
, assertInvoked
, and a few others. Be sure to check out the full list of available assertions in the project’s readme for details and examples.
Related: Tips to Speed up Your Phpunit Tests
You can learn more about this package, get full installation instructions, and view the source code on GitHub at timacdonald/callable-fake.
Filed in:
Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.