PHP Callable Fake Library

News

May 12th, 2020

PHP Callable Fake Library

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:

1// Before, you might collect callables to assert later...
2public function testEachLoopsOverAllDependencies(): void
3{
4 // arrange
5 $received = [];
6 $expected = factory(Dependency::class)->times(2)->create();
7 $repo = $this->app[DependencyRepository::class];
8 
9 // act
10 $repo->each(function (Dependency $dependency) use (&$received): void {
11 $received[] = $dependency;
12 });
13 
14 // assert
15 $this->assertCount(2, $received);
16 $this->assertTrue($expected[0]->is($received[0]));
17 $this->assertTrue($expected[1]->is($received[1]));
18}

Using this package you can use something like the following instead:

1public function testEachLoopsOverAllDependencies(): void
2{
3 // arrange
4 $callable = new CallableFake();
5 $expected = factory(Dependency::class)->times(2)->create();
6 $repo = $this->app[DependencyRepository::class];
7 
8 // act
9 $repo->each($callable);
10 
11 // assert
12 $callable->assertTimesInvoked(2);
13 $callable->assertCalled(function (Depedency $dependency) use ($expected): bool {
14 return $dependency->is($expected[0]);
15 });
16 $callable->assertCalled(function (Dependency $dependency) use ($expected): bool {
17 return $dependency->is($expected[1]);
18 });
19}

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:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.