Laravel项目中如何优雅地跳过PHPUnit中的高开销测试方法
更优雅的Laravel测试条件跳过方案
方案1:使用PHPUnit原生的跳过测试方法
你之前的写法会把非本地环境的对应测试标记为已通过,不符合实际测试状态,推荐用PHPUnit内置的markTestSkipped方法,测试报告中会明确标记为「已跳过」,方便后续统计排查:
class HomePageTest extends TestCase { use WithFaker, RefreshDatabase; /** @test */ public function something_testing() { // 非本地环境直接跳过测试 if (app()->environment() !== 'local') { $this->markTestSkipped('高开销测试仅在本地环境运行'); } $response = $this->get('/expensive-service'); $response->assertStatus(200); } }
注意优先用app()->environment()方法判断环境,不要直接调用env(),避免配置缓存后env()返回null的问题。
方案2:使用Laravel内置的条件测试注解(推荐)
Laravel 8及以上版本提供了开箱即用的测试条件注解,不需要写任何逻辑判断,一行注解就可以实现按环境过滤测试:
use Illuminate\Testing\Requirements\RequiresEnvironment; class HomePageTest extends TestCase { use WithFaker, RefreshDatabase; /** @test */ #[RequiresEnvironment('local')] public function something_testing() { $response = $this->get('/expensive-service'); $response->assertStatus(200); } }
如果需要同时限制多个环境,也可以传入数组:#[RequiresEnvironment(['local', 'testing'])]
方案3:批量复用跳过逻辑
如果有多个测试方法都需要仅在本地运行,可以把逻辑封装成公共方法或者Trait,避免重复写判断代码:
// 新建Trait app/Tests/OnlyRunsInLocal.php trait OnlyRunsInLocal { public function setUpOnlyRunsInLocal(): void { if (app()->environment() !== 'local') { $this->markTestSkipped('当前测试仅允许在本地环境运行'); } } } // 测试类中直接引入即可对所有方法生效 class HomePageTest extends TestCase { use WithFaker, RefreshDatabase, OnlyRunsInLocal; /** @test */ public function something_testing() { $response = $this->get('/expensive-service'); $response->assertStatus(200); } }
内容的提问来源于stack exchange,提问作者friday
相关产品推荐
相关产品推荐

