【发布时间】:2019-01-02 00:16:14
【问题描述】:
我有一个 Laravel 设置,我尝试使用测试驱动开发来构建所有内容。
设置
我有一个迁移,我在其中创建了一个类别表,该表可以是其他类别的父级或子级。当我删除父类别时,所有子类别都应成为根类别。为此,我创建了一个外键,其中 set null 作为 onDelete 的值。
问题
当我在 MySQL 中测试此行为时,它按预期工作,但是当我使用 PHPunit 运行测试时,它失败了。谁能帮我弄清楚我在哪里犯了错误,或者这根本不可能?
迁移
Schema::create('categories', function(Blueprint $table) {
$table->increments('id');
$table->string('name', 100);
$table->unsignedInteger('parent_id')->nullable();
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('categories')->onDelete('set null');
});
测试文件
namespace Tests\Unit;
use App\Models\Category;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class CategoryTest extends TestCase
{
/**
* @test
*/
public function aCategoryBecomesRootWhenParentIsDeleted()
{
$category = Category::create(['name' => 'test_category_6']);
$child_category = Category::create(['name' => 'test_category_7', 'parent_id' => $category->id]);
$category->delete();
$this->assertDatabaseHas('categories', ['id' => $child_category->id, 'parent_id' => NULL]);
}
}
phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="DB_CONNECTION" value="sqlite"></env>
<env name="DB_DATABASE" value=":memory:"></env>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="MAIL_DRIVER" value="array"/>
</php>
</phpunit>
【问题讨论】:
-
你为测试设置了什么数据库? sqlite?
-
@lagbox 是的。我也添加了我的 PHPunit 配置,也许那里有更多信息。
-
sqlite 默认在外键上有这个功能吗?我觉得这是必须启用的东西
-
我认为您需要启用外键,因为默认情况下它们是关闭的。 默认禁用外键约束(为了向后兼容)... source.
-
@lagbox 很奇怪,我刚刚使用 sqlite 数据库和 sqlite db 浏览器对其进行了测试,它按预期工作。也许不是为了 PHPunit 测试,但我想我现在可以找到一个解决方案,感谢你和 Kyslik!