Home  >  Article  >  Backend Development  >  【callable-fake】Fake your callable function to speed up testing

【callable-fake】Fake your callable function to speed up testing

藏色散人
藏色散人forward
2020-05-19 13:33:211786browse

Callable fake is a PHP testing utility by Tim Macdonald that "allows you to fake, capture and assert calls to callables/closures". In some cases, this package can help allow developers to pass a callable in tests.

It has an API inspired by Laravel fiction as shown below:

// 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:

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]);
    });
}

The package Assertions such as assertCalled, assertNotCalled, assertInvoked, etc. are provided. For details and examples, be sure to check out the Full list of available assertions in the project readme.

You can learn more about this package on GitHub, get complete installation instructions, and view the source code at timacdonald/callable-fake.

The above is the detailed content of 【callable-fake】Fake your callable function to speed up testing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete