安装方法只运行一次

时间:2017-04-03 13:09:16

标签: php laravel phpunit

我有:

null

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

现在在很多测试类中,我有一个1. IntegrationTestCase extends TestCase 2. UnitTestCase extends TestCase 3. AcceptanceTestCase extends TestCase 方法,它准备所需的数据和服务,并将它们分配给类变量:

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...; } } 针对每个测试运行而不是我想要做什么,以及setUp方法确实需要花费很长时间才会乘以测试方法的数量。

使用setUp会产生问题,因为现在Laravel中的低级方法和类不可用。

3 个答案:

答案 0 :(得分:8)

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

我遇到了一个问题,我想在运行测试之前迁移数据库,但我不想在每次测试后迁移数据库,因为执行时间太长了。

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

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;
        }
    }
}

答案 1 :(得分:0)

萨曼·侯赛尼(Saman Hosseini)和类似人提供的解决方案对我来说并不适用。使用static属性标记下一个测试类的重置。

为克服这个问题,我编写了单独的测试类来测试测试数据库连接并一次初始化测试数据库,并确保它在所有其他测试之前运行

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;

/**
 * @runTestsInSeparateProcesses
 */
class DatabaseConnectionTest extends TestCase
{
    /**
     * Test the database connection
     *
     * @return void
     */
    public function testDatabaseConnection()
    {
        $pdo = DB::connection()->getPdo();
        $this->assertNotNull($pdo);
    }

    /**
     * Initialize the test database for once
     *
     * @return void
     */
    public function testInititializeTestDatabase()
    {
        Artisan::call('migrate:fresh');
        Artisan::call('db:seed');
    }
}

答案 2 :(得分:-1)

我不确定您对setUpBeforeClass看到的问题是静态的,除了Mark Ba​​ker提到的问题。不过,我猜你确实知道自己在做什么。以下是可能的使用示例。

class BeforeAllTest extends PHPUnit_Framework_TestCase
{
    private static $staticService;
    private $service; // just to use $this is tests

    public static function setUpBeforeClass() {
        self::createService();
    }

    public static function createService(){
        self::$staticService = 'some service';
    }

    /**
     * just to use $this is tests
     */
    public function setUp(){
        $this->service = self::$staticService;
    }

    public function testService(){
        $this->assertSame('some service', $this->service);
    }
}

更新:您可以在https://phpunit.de/manual/current/en/database.html看到一些类似的方法(搜索“提示:使用您自己的抽象数据库TestCase”)。我确信你已经在使用它,因为你正在进行密集的数据库测试。但是没有人限制这种方式只用于db-issues。

UPDATE2:好吧,我想你必须使用像self::createService而不是$this->createService的smth(我已经更新了上面的代码)。

相关问题