全域掛鉤

前面討論過,掛鉤讓你簡化測試流程,並自動化你可能在執行測試前或後執行的重複性工作。然而,如果多個測試檔案內的掛鉤都相同,你可能會希望定義「全域」掛鉤來避免程式碼重複。全域掛鉤會定義在你的 Pest.php 設定檔中。

例如,如果你需要在 Feature 資料夾內的每個測試前執行某些資料庫操作,你可以在 Pest.php 設定檔中使用 beforeEach() 掛鉤。

1pest()->extend(TestCase::class)->beforeEach(function () {
2 // Interact with your database...
3})->group('integration')->in('Feature');

此外,你可以定義在整個測試系列執行前或後執行的全域掛鉤,不論資料夾或群組為何。

1pest()->beforeEach(function () {
2 // Interact with your database...
3});

事實上,在 掛鉤 文件中提到的任何掛鉤都可以在你的 Pest.php 設定檔中使用。

1pest()->extend(TestCase::class)->beforeAll(function () {
2 // Runs before each file...
3})->beforeEach(function () {
4 // Runs before each test...
5})->afterEach(function () {
6 // Runs after each test...
7})->afterAll(function () {
8 // Runs after each file...
9})->group('integration')->in('Feature');

Pest.php 設定檔中定義的任何 before* 掛鉤都將在個別測試檔案中定義的掛鉤前執行。類似地,在 Pest.php 設定檔中指定的任何 after* 掛鉤都將在個別測試檔案中定義的任何掛鉤後執行。


在設定測試系列時,可能必須模擬特定功能或物件,以便分離正在測試的程式碼,並模擬某些條件或行為。這可以使用模擬程式庫或架構來完成,例如 Mockery:模擬