設定測試
Pest.ph
檔案是一個設定檔案,用於定義你的測試套件設定。這個檔案位於你專案中的 test
目錄,當你執行你的測試時,Pest 會自動載入它。雖然你可以在這個檔案中定義 全域 Hook 或 自訂預期,但它的主要目的是為了指定在你的測試套件中使用的基本測試類別。
在使用 Pest 時,提供給測試功能的閉包中可用的 $this
變數會繫結到一個特定的測試案例類別,通常是 PHPUnit\Framework\TestCase
。這可以確保使用 Pest 函式風格編寫的測試案例,可以存取 PHPUnit 的底層斷言 API,簡化與更熟悉 PHPUnit 測試框架的其他開發人員的協作。
1it('has home', function () {2 echo get_class($this); // \PHPUnit\Framework\TestCase3 4 $this->assertTrue(true);5});
但是,你可以將特定資料夾,甚至你的整個測試套件,關聯到另一個基本測試案例類別,從而變更測試中的 $this
的值。要完成這項工作,你可以使用 pest()
函數,以及你 Pest.php
設定檔案中的 in()
方法。
1// tests/Pest.php2pest()->extend(Tests\TestCase::class)->in('Feature');3 4// tests/Feature/ExampleTest.php5it('has home', function () {6 echo get_class($this); // \Tests\TestCase7});
此外,Pest 支援 in()
方法中的 glob 模式。這允許你使用單一模式指定多個目錄或檔案。glob 模式是可以比對各種檔案路徑的字串表示,就像萬用字元。如果你不熟悉 glob 模式,請參閱 PHP 手冊 在此。
1// tests/Pest.php2pest()->extend(Tests\TestCase::class)->in('Feature/*Job*.php');3 4// This will apply the Tests\TestCase to all test files in the "Feature" directory that contains "Job" in their filename.
另一個更複雜的範例是使用模式來比對不同模組中的多個目錄,同時套用多個測試案例類別和特質
1// tests/Pest.php2pest()3 ->extend(DuskTestCase::class)4 ->use(DatabaseMigrations::class)5 ->in('../Modules/*/Tests/Browser');6 7// This will apply the DuskTestCase class and the DatabaseMigrations trait to all test files within any module's "Browser" directory.
在你的基本測試案例類別中定義為 public
或 protected
的任何方法,都可以在測試閉包內存取。
1use PHPUnit\Framework\TestCase as BaseTestCase; 2 3// tests/TestCase.php 4class TestCase extends BaseTestCase 5{ 6 public function performThis(): void 7 { 8 // 9 }10}11 12// tests/Pest.php13pest()->extend(TestCase::class)->in('Feature');14 15// tests/Feature/ExampleTest.php16it('has home', function () {17 $this->performThis();18});
與類別非常像,特質可以連結到測試或資料夾。例如,在 Laravel 中,你可以使用 RefreshDatabase
特質來在每次測試前重設資料庫。要將特質包含在你的測試中,請將特質的名稱傳遞給 pest()->use()
方法。
1<?php2 3use Tests\TestCase;4use Illuminate\Foundation\Testing\RefreshDatabase;5 6pest()->extend(TestCase::class)->use(RefreshDatabase::class)->in('Feature');
要將特定測試與特定的測試案例類別或特質關聯,你可以使用 pest()->extend()
和 pest()->use()
方法在那個特定的測試檔案中,省略使用 in()
方法。
1pest()->extend(Tests\MySpecificTestCase::class);2 3it('has home', function () {4 echo get_class($this); // \Tests\MySpecificTestCase5});
接下來,測試套件設定時可用的一項功能是群組資料夾的功能。使用時,此功能允許您使用 --group
選項篩選執行過的測試: 群組測試