从 PHP 单元测试中跳过昂贵的方法

Skip expensive methods from PHP unit testing

我想在生产 Lavavel 项目中跳过昂贵的方法。我就是这样跳过的

class HomePageTest extends TestCase
{
   use WithFaker, RefreshDatabase;
    /** @test */
    public function something_testing()
    {
      if (  env('APP_ENV') == 'local' ) {
        $response = $this->get('/expensive-service');
        $response->assertStatus(200);
      } else {
         $this->assertTrue(true);
      }
    }
}


以上代码有效。但是,我觉得有一些优雅的方法可以跳过某些州的测试方法。

在 PHP 单元中,您可以使用 groups 标记测试,例如

class HomePageTest extends TestCase
{
   use WithFaker, RefreshDatabase;
    /** 
     * @test 
     * 
     * @group notProduction
     */
    public function something_testing()
    {
        $response = $this->get('/expensive-service');
        $response->assertStatus(200);
    }
}

Laravel 带有 phpunit.xml.dist,您可以按如下方式更新该文件:

<groups>
  <exclude>
    <group>notProduction</group>
  </exclude>
</groups>

关于配置选项的文档是here

对于本地测试,您可以创建一个没有排除选项的本地 phpunit.xml

Laravel 测试将使用 phpunit.xml(如果存在),否则它们会回退到使用 phpunit.xml.dist,这样您就可以控制在每个环境中运行的测试配置