安装方法只运行一次

Ste*_*ess 2 php phpunit laravel

我有:

1. IntegrationTestCase extends TestCase  
2. UnitTestCase extends TestCase
3. AcceptanceTestCase extends TestCase  
Run Code Online (Sandbox Code Playgroud)

在这些中,我有很多非静态方法,它们在很多测试中使用.我的所有Test类都扩展了这3个类中的一个.

现在在很多测试类中,我有一个setUp方法,它准备所需的数据和服务,并将它们分配给类变量:

class SomeTestClass extends IntegrationTestCase
{
    private $foo;

    public function setUp()
    {
        parent::setUp();

        $bar = $this->createBar(...);
        $this->foo = new Foo($bar);
    }

    public function testA() { $this->foo...; }  
    public function testB() { $this->foo...; }
}
Run Code Online (Sandbox Code Playgroud)

setUp每个测试都会遇到问题,无法完成我想要做的事情,如果setUp需要花费很长时间,那么这个方法会乘以测试方法的数量.

使用public function __construct(...) { parent::__construct(..); ... }会产生问题,因为现在Laravel中的低级方法和类不可用.

小智 11

对于遇到此问题的下一个人:

我有一个问题,我想在运行我的测试之前迁移数据库,但我不希望在每次单个测试后迁移数据库,因为执行时间太高了.

我的解决方案是使用静态属性来检查数据库是否已经迁移:

class SolutionTest extends TestCase
{
    protected static $wasSetup = false;

    protected function setUp()
    {
        parent::setUp();

        if ( ! static::$wasSetup) {
            $this->artisan('doctrine:schema:drop', [
                '--force' => true
            ]);

            $this->artisan('doctrine:schema:create');

            static::$wasSetup = true;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)