Linux 上测试 Laravel 的完整流程
一 环境准备与初始化
composer install(开发环境保留 dev 依赖;生产环境加 --no-dev 并做 optimize-autoloader)php artisan key:generatephp artisan config:clear 以避免缓存干扰。二 运行测试与常用命令
./vendor/bin/phpunit 或 php artisan test(推荐,语义更清晰)php artisan test --filter ExampleTestphp artisan test tests/Feature 或 php artisan test tests/Unitphp artisan test --parallelphp artisan test --help(可结合 --stop-on-failure、--coverage 等)php artisan make:test HomePageTest<?php
namespace Tests\Feature;
use Tests\TestCase;
class HomePageTest extends TestCase
{
public function test_homepage_status(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
php artisan test --filter HomePageTest三 测试类型与示例
<?php
namespace Tests\Unit;
use Tests\TestCase;
use App\Models\Post;
class PostTest extends TestCase
{
public function test_title_accessor(): void
{
$post = new Post(['title' => 'hello']);
$this->assertEquals('Hello', $post->title); // 假设有访问器 ucfirst
}
}
<?php
namespace Tests\Feature;
use Tests\TestCase;
class PostApiTest extends TestCase
{
public function test_can_create_post(): void
{
$payload = ['title' => 'Test', 'content' => 'Content'];
$response = $this->postJson('/api/posts', $payload);
$response->assertStatus(201)->assertJsonFragment($payload);
}
}
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
class PostFeatureTest extends TestCase
{
use DatabaseMigrations;
public function test_create_post_and_see_in_list(): void
{
$this->post('/posts', ['title' => 'A', 'content' => 'B']);
$this->get('/posts')->assertSee('A');
}
}
<?php
namespace Tests\Feature;
use App\Events\MyEvent;
use Tests\TestCase;
class EventTest extends TestCase
{
public function test_event_dispatched_and_listener_handled(): void
{
// 可结合 Mockery 断言监听被调用
event(new MyEvent('test'));
// 断言数据库/缓存/日志等副作用
}
}
四 数据库与存储测试要点
<php> 段设置):<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
use DatabaseTransactions; 可让每个测试在事务中运行,结束后自动回滚,避免污染数据。use DatabaseMigrations; 会在每个测试前执行迁移,适合需要真实表结构的场景。filesystems.disks.local.root 指向 storage/framework/testing,并在测试后清理。五 性能与负载测试建议
use Illuminate\Support\Facades\Benchmark;
Benchmark::measure('Heavy job', function () {
// 要测量的逻辑
});
php artisan test --parallel 并行执行测试。