【 callable-fake】虛構你的可呼叫函數以加速測試

2020-07-16 10:05:54
Callable fake 是 Tim Macdonald 的一個 PHP 測試實用程式,它 「允許您偽造、捕獲和斷言對可呼叫 / 閉包的呼叫」。在某些情況下,此包可以幫助在測試中允許開發人員傳遞一個 callable。

它有一個受 Laravel 虛構啟發的 API,如下所示:

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

使用此軟體包,您可以使用類似以下內容的內容:

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

該包提供了諸如 assertCalled、assertNotCalled、assertInvoked 等斷言。有關詳細資訊和範例,請務必檢視專案讀我檔案中的可用 assertions 的完整列表

你可以在 GitHub 上了解更多關於此軟體包的資訊,獲取完整的安裝說明,並在 timacdonald/callable-fake 上檢視原始碼。

以上就是【 callable-fake】虛構你的可呼叫函數以加速測試的詳細內容,更多請關注TW511.COM其它相關文章!