News

PHP Callable Fake Library

Published
PHP Callable Fake Library image

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.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Agent Run Observability in Laravel AI SDK 0.11 image

Agent Run Observability in Laravel AI SDK 0.11

Read article
Debounced Queued Event Listeners in Laravel image

Debounced Queued Event Listeners in Laravel

Read article
Statamic Mailables Viewer Previews Laravel Emails in the Control Panel image

Statamic Mailables Viewer Previews Laravel Emails in the Control Panel

Read article
Laravel Tackle: Run an AI Coding Agent in Your Laravel App image

Laravel Tackle: Run an AI Coding Agent in Your Laravel App

Read article
Queue::forward(): Reroute Laravel Queues in One Place image

Queue::forward(): Reroute Laravel Queues in One Place

Read article
Laravel Read-Through Filesystem: Lazy Storage Migration image

Laravel Read-Through Filesystem: Lazy Storage Migration

Read article