【 callable-fake】虚构你的可调用函数以加速测试

Callable fake 是 Tim Macdonald 的一个 PHP 测试实用程序,它 “允许您伪造、捕获和断言对可调用 / 闭包的调用”,在某些情况下,此包可以帮助在测试中允许开发人员传递一个 callable。

它有一个受 Laravel 虚构启发的 API,如下所示:

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

使用此软件包,您可以使用类似以下内容的内容:

  1. public 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. // act
  8. $repo->each($callable);
  9. // assert
  10. $callable->assertTimesInvoked(2);
  11. $callable->assertCalled(function (Depedency $dependency) use ($expected): bool {
  12. return $dependency->is($expected[0]);
  13. });
  14. $callable->assertCalled(function (Dependency $dependency) use ($expected): bool {
  15. return $dependency->is($expected[1]);
  16. });
  17. }

该包提供了诸如 assertCalled、assertNotCalled、assertInvoked 等断言,有关详细信息和示例,请务必查看项目自述文件中的可用 assertions 的完整列表。

你可以在 GitHub 上了解更多关于此软件包的信息,获取完整的安装说明,并在 timacdonald/callable-fake 上查看源代码。