【问题标题】:Artisan 'Nothing to migrate' error with PHPUnitPHPUnit 的 Artisan 'Nothing to migrate' 错误
【发布时间】:2015-08-03 21:34:50
【问题描述】:

概要

我有一个包含database/migrations 目录的包,其中包含许多迁移。我有一个tests 目录,其中包含一个带有一个断言的测试。

我希望使用 对迁移进行单元测试。

出现的问题

我运行 PHP 单元但我的测试失败:

$ phpunit
PHPUnit 4.6.6 by Sebastian Bergmann and contributors.

Configuration read from /var/www/.../phpunit.xml

F

Time: 594 ms, Memory: 15.25Mb

There was 1 failure:

1) MigrationTest::testTableExists
Failed asserting that false is true.

/var/www/../tests/MigrationTest.php:31

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

此命令不会在测试数据库中创建任何表,它会在测试数据库中创建迁移表。

然后我尝试在命令行上运行迁移:

$ php artisan migrate --env=testing --path=/vendor/../database/migrations/
Migration table created successfully.
Migrated: 2015_.._table
Migrated: 2015_.._table
Migrated: 2015_.._table

--env=testing 参数已被完全忽略,我的表已迁移到生产数据库(注意:生产数据库是指开发,但默认/生产设置使用不正确

我将开发数据库凭据添加到phpunit.xml

<php>
    <env name="APP_ENV" value="testing"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="QUEUE_DRIVER" value="sync"/>
    <env name="DB_DATABASE" value="test"/>
    <env name="DB_USERNAME" value="test"/>
    <env name="DB_PASSWORD" value="test"/>
</php>

我的测试用例是:

<?php

class MigrationTest extends \Illuminate\Foundation\Testing\TestCase
{
    public function createApplication()
    {
        $app = require __DIR__. '/../../../../bootstrap/app.php';
        $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

        return $app;
    }

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

        $this->artisan('migrate', ['--env' => 'testing', '--path' => __DIR__.'/../database/migrations']);
    }

    public function tearDown()
    {
        //$this->artisan('migrate:rollback', ['--path' => __DIR__.'/../']);

        parent::tearDown();
    }

    public function testTableExists()
    {
        $hasTable = Schema::hasTable('table_name');

        $this->assertTrue($hasTable);
    }
}

在测试期间,我可以使用dd 转储出env() 数据,并且数据库凭据正确设置为test, test and test

我真的很困惑如何解决这个问题。

【问题讨论】:

  • 我遇到了同样的问题,并且得出的结论是 runDatabaseMigration() 在 setUp() 方法完成后被触发。除了将其提取到自定义设置方法并从每个测试中调用之外,我还没有找到一个优雅的解决方案。

标签: phpunit php unit-testing phpunit laravel-5 laravel-artisan


【解决方案1】:

其中一个问题是使用--path,因为迁移只能向上迁移而不能向下迁移。因此,最佳做法是使用以下任一方法:

  • Artisan vendor:publish 并复制到 ./tests/,或
  • /vendor/&lt;namespace&gt;/&lt;package&gt;/tests/ 目录添加到PHPUnit

我选择了后者,因为这样可以保持应用程序更整洁,并且意味着只需要维护包路径以及对 composer.json 的任何更改。

所以本质上是在 phpunit.xml 中添加多个 &lt;directory&gt; 定义。

<testsuites>
    <testsuite name="Application Test Suite">
        <directory>./tests/</directory>
        <directory>./vendor/VENDOR/PACKAGE/tests/</directory>
    </testsuite>
</testsuites>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 2016-05-14
    • 2020-10-23
    • 2016-10-14
    • 2018-08-04
    • 2018-11-18
    • 2015-12-19
    • 2017-09-27
    相关资源
    最近更新 更多