1. 准备Linux环境
在Linux系统上运行Laravel测试前,需确保已安装以下核心组件:
mbstring、openssl、pdo_mysql、tokenizer、xml、gd、bcmath等)。可通过包管理器安装(如Ubuntu/Debian使用sudo apt install php php-cli php-mbstring php-openssl php-pdo-mysql php-tokenizer php-xml php-gd php-bcmath,CentOS使用sudo yum install php php-mbstring php-openssl php-pdo php-mysqlnd php-tokenizer php-xml php-gd php-bcmath)。curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer全局安装,验证composer --version输出版本号。public目录(Nginx配置示例:server { listen 80; server_name yourdomain.com; root /path/to/laravel/public; index index.php index.html; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } })。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;)。2. 配置Laravel项目
composer create-project --prefer-dist laravel/laravel your_project_name)或克隆现有项目(git clone https://github.com/laravel/laravel.git your_project_name)。.env.example为.env(cp .env.example .env),修改数据库连接信息(DB_CONNECTION=mysql、DB_HOST=127.0.0.1、DB_PORT=3306、DB_DATABASE=laravel_test、DB_USERNAME=laravel_user、DB_PASSWORD=your_password),并通过php artisan key:generate生成应用密钥(.env中APP_KEY需为base64:开头的随机字符串)。storage(日志、缓存、上传文件)和bootstrap/cache(配置缓存)目录需Web服务器用户(如www-data)可写。执行sudo chown -R www-data:www-data /path/to/laravel(将项目所有者设为Web用户),sudo chmod -R 775 /path/to/laravel/storage、sudo chmod -R 775 /path/to/laravel/bootstrap/cache(设置目录权限)。3. 安装PHPUnit
Laravel默认集成PHPUnit,无需单独安装。若需升级或重新安装,可通过Composer执行composer require --dev phpunit/phpunit。项目根目录下的phpunit.xml文件用于配置PHPUnit(如测试目录、输出格式、测试数据库等),默认已配置好基本设置。
4. 编写测试用例
Laravel的测试目录为tests/,分为Unit(纯单元测试)和Feature(功能测试/集成测试):
php artisan make:test ExampleUnitTest --unit(生成tests/Unit/ExampleUnitTest.php,继承Tests\Unit\TestCase,不加载Laravel环境);功能测试用php artisan make:test ExampleFeatureTest(生成tests/Feature/ExampleFeatureTest.php,继承Tests\TestCase,加载Laravel环境)。test_开头或添加@test注解,使用断言验证预期结果。例如:
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleUnitTest extends TestCase {
public function test_addition() {
$this->assertEquals(4, 2 + 2); // 断言2+2等于4
}
}
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleFeatureTest extends TestCase {
use RefreshDatabase; // 每次测试前后自动迁移/重置数据库
public function test_home_page() {
$response = $this->get('/'); // 发送GET请求到首页
$response->assertStatus(200); // 断言状态码为200
}
public function test_user_registration() {
$user = \App\Models\User::factory()->create(); // 使用工厂创建测试用户
$response = $this->get("/user/{$user->id}"); // 访问用户详情页
$response->assertSee($user->name); // 断言页面包含用户名
}
}
5. 运行测试
./vendor/bin/phpunit(Linux/macOS)或vendor\bin\phpunit(Windows),PHPUnit会自动查找并执行tests/目录下的所有测试用例。--filter指定测试类或方法,如./vendor/bin/phpunit --filter ExampleUnitTest(运行ExampleUnitTest类)、./vendor/bin/phpunit --filter test_addition(运行test_addition方法)。6. 高级测试(可选)
RefreshDatabase trait(use RefreshDatabase;)自动处理数据库迁移和重置,确保每次测试在干净的数据库环境中运行。例如:public function test_user_creation() {
$user = \App\Models\User::factory()->create(['email' => 'test@example.com']);
$this->assertDatabaseHas('users', ['email' => 'test@example.com']); // 断言数据库中存在该用户
}
get、post、put、delete等方法模拟HTTP请求,结合assertStatus(断言状态码)、assertSee(断言页面包含内容)、assertRedirect(断言重定向)等断言验证响应。例如:public function test_login() {
$response = $this->post('/login', ['email' => 'user@example.com', 'password' => 'password']);
$response->assertRedirect('/dashboard'); // 断言登录后重定向到仪表盘
}
.github/workflows/php.yml文件:name: PHP CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
services:
mysql:
image: mysql:8.0
env:
MYSQL_DATABASE: laravel_test
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: laravel_user
MYSQL_PASSWORD: your_password
ports:
- 3306:3306
volumes:
- db_data:/var/lib/mysql
steps:
- uses: actions/checkout@v2
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.2'
- name: Install dependencies
run: composer install --no-progress --prefer-dist --optimize-autoloader
- name: Run tests
env:
DB_CONNECTION: mysql
DB_HOST: 127.0.0.1
DB_PORT: 3306
DB_DATABASE: laravel_test
DB_USERNAME: laravel_user
DB_PASSWORD: your_password
run: ./vendor/bin/phpunit
volumes:
db_data: