php - 设置方法只运行一次

标签 php laravel phpunit

我有:

1. IntegrationTestCase extends TestCase  
2. UnitTestCase extends TestCase
3. AcceptanceTestCase extends TestCase  

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

现在在很多测试类(class)中我都有一个 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方法确实需要很长时间,这乘以测试方法的数量。

使用 public function __construct(...) { parent::__construct(..); ... }造成了一个问题,因为现在 Laravel 的低级方法和类不可用。

最佳答案

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

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

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

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

关于php - 设置方法只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43185511/

相关文章:

php -/#!/在 URL 中是什么意思?

php - php 和 javascript 之间的 var 传输

php - Laravel 在保存前生成 slug

php - SQL - 组织多个发布/记录类型的最有效方法

PHPUnit 无法打开文件

php - Laravel 事件模拟

php - Codeigniter:何时使用模型与库?

php - PHP 代码中的 SQL 语法错误,即使命令在命令行中运行

authentication - 每次调用 Auth::user() 时 Laravel 都会查询数据库吗?

PHPUnit 确保特征满足接口(interface)