1. 準備Debian系統環境
在Debian上測試Laravel代碼前,需先安裝必要的依賴(PHP、Composer、Web服務器、數據庫等)。更新系統包并安裝PHP及擴展(如php-cli
、php-mysql
、php-curl
等)、Composer、Nginx/Apache、MySQL/MariaDB。例如,安裝PHP及相關擴展可使用:
sudo apt update && sudo apt install -y php php-cli php-fpm php-json php-mysql php-zip php-gd php-mbstring php-curl php-xml php-bcmath
安裝Composer:
curl -sS https://getcomposer.org/installer | sudo mv composer.phar /usr/local/bin/composer
這些步驟確保Laravel及測試工具能正常運行。
2. 搭建Laravel測試環境
使用Composer創建新的Laravel項目或進入現有項目目錄:
laravel new my-laravel-app # 新建項目
cd my-laravel-app
配置Web服務器(以Nginx為例),創建/etc/nginx/sites-available/my-laravel-app
文件,內容如下:
server {
listen 80;
server_name localhost; # 替換為你的域名/IP
root /var/www/my-laravel-app/public;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # 根據PHP版本調整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
}
啟用配置并重啟Nginx:
sudo ln -s /etc/nginx/sites-available/my-laravel-app /etc/nginx/sites-enabled
sudo nginx -t && sudo systemctl restart nginx
配置數據庫(MySQL為例),登錄MySQL并創建數據庫及用戶:
CREATE DATABASE laravel_test;
CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON laravel_test.* TO 'laravel_user'@'localhost';
FLUSH PRIVILEGES;
修改.env
文件,設置數據庫連接和測試環境變量:
APP_ENV=testing
APP_DEBUG=true
DB_CONNECTION=mysql
DB_DATABASE=laravel_test
DB_USERNAME=laravel_user
DB_PASSWORD=your_password
生成應用密鑰:
php artisan key:generate
運行數據庫遷移:
php artisan migrate
完成環境搭建后,即可開始編寫和運行測試。
3. 編寫Laravel測試用例
Laravel的測試文件位于tests
目錄,分為Feature
(功能測試)和Unit
(單元測試)子目錄??墒褂肁rtisan命令快速生成測試類:
php artisan make:test ExampleTest # 生成功能測試
php artisan make:test UserTest --unit # 生成單元測試
測試類繼承Tests\TestCase
,包含setUp()
方法(初始化測試環境)和測試方法(以test
開頭)。示例如下:
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_homepage_returns_200()
{
$response = $this->get('/');
$response->assertStatus(200); // 斷言狀態碼為200
}
}
namespace Tests\Unit;
use Tests\TestCase;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
class UserTest extends TestCase
{
use RefreshDatabase; // 每次測試前刷新數據庫
public function test_user_creation()
{
$user = User::factory()->create(); // 使用工廠創建用戶
$this->assertDatabaseHas('users', ['email' => $user->email]); // 斷言數據庫存在該用戶
}
}
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use App\Models\Post;
class PostTest extends TestCase
{
use RefreshDatabase;
public function test_create_post()
{
$response = $this->post('/posts', [
'title' => 'Test Post',
'content' => 'This is a test post.'
]);
$response->assertRedirect('/posts'); // 斷言重定向到帖子列表
$this->assertDatabaseHas('posts', ['title' => 'Test Post']); // 斷言帖子已保存
}
}
更多斷言方法可參考Laravel文檔(如assertSee
、assertJson
等)。
4. 運行Laravel測試
Laravel提供了兩種運行測試的方式:
php artisan test
該命令會自動運行tests
目錄下的所有測試用例,并輸出詳細結果(包括通過/失敗的測試數量、失敗原因)。添加--verbose
選項可查看更詳細的執行信息:
php artisan test --verbose
vendor/bin/phpunit
或運行指定測試類/方法:
vendor/bin/phpunit tests/Feature/ExampleTest.php # 運行指定測試類
vendor/bin/phpunit tests/Feature/ExampleTest.php --filter test_homepage_returns_200 # 運行指定測試方法
運行測試時,Laravel會自動處理數據庫遷移(通過RefreshDatabase
trait)和環境切換(APP_ENV=testing
),確保測試環境與生產環境隔離。
5. 高級測試技巧
Mockery
或Laravel的shouldReceive
方法模擬API調用、郵件發送等外部依賴,避免測試時依賴真實服務。例如:\Mail::fake(); // 模擬郵件發送
$user = User::factory()->create();
// 執行觸發郵件的操作(如注冊)
Mail::assertSent(WelcomeEmail::class, function ($mail) use ($user) {
return $mail->hasTo($user->email); // 斷言郵件發送給正確用戶
});
php artisan test --parallel
命令并行運行測試,加快測試速度(需安裝pcntl
擴展)。Benchmark
工具測量代碼片段執行時間,或使用PHPUnit的性能測試功能(如@group performance
標記性能測試類)。