gpt4 book ai didi

php - 在套件中的每个测试之前运行设置代码

转载 作者:行者123 更新时间:2023-11-28 20:39:03 25 4
gpt4 key购买 nike

我有一个正在开发的 Laravel 5 应用程序,它有两个测试套件:UnitFunctional。我在 phpunit.xml 中定义了这些:

<testsuite name="Unit">
<directory>./tests/unit</directory>
</testsuite>
<testsuite name="Functional">
<directory>./tests/functional</directory>
</testsuite>

要使功能测试正确运行,它们需要有一个有效的数据库来处理。这意味着在运行功能测试之前执行一些设置以迁移数据库。

通常我会在我的测试中使用 DatabaseMigrations 特性来确保在每次测试之前迁移数据库。不幸的是,这大大减慢了我们的测试速度(我们有数百个)。我将测试切换为使用 DatabaseTransactions 特性,这使它们运行得更快,但现在在运行测试之前不会迁移数据库。如果我在项目的新克隆上运行测试套件,它会失败,因为我在运行功能测试套件之前没有迁移数据库。

对此的明显解决方案是将 $this->artisan('migrate'); 添加到 tests/TestCase.php< 的 setUp 方法中。但这有两个问题:

  1. 这会导致在每次测试之前迁移数据库,这是我一开始就试图避免的。

  2. 这还试图在运行单元测试套件时迁移数据库,这显然不理想。

确保在运行任何测试之前迁移功能测试的数据库但仅针对功能测试的最佳方法是什么?

最佳答案

您可以创建一个继承自 Laravel 的 TestCase 的基本 testClase 类,只有您的 Functional 套件类可以继承新的,并在您的新类中添加:

/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
return self::initialize();
}

private static $configurationApp = null;
public static function initialize(){

if(is_null(self::$configurationApp)){
$app = require __DIR__.'/../bootstrap/app.php';

$app->loadEnvironmentFrom('.env.testing');

$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

if (config('database.default') == 'sqlite') {
$db = app()->make('db');
$db->connection()->getPdo()->exec("pragma foreign_keys=1");
}

Artisan::call('migrate');
Artisan::call('db:seed');

self::$configurationApp = $app;
return $app;
}

return self::$configurationApp;
}

public function tearDown()
{
if ($this->app) {
foreach ($this->beforeApplicationDestroyedCallbacks as $callback) {
call_user_func($callback);
}

}

$this->setUpHasRun = false;

if (property_exists($this, 'serverVariables')) {
$this->serverVariables = [];
}

if (class_exists('Mockery')) {
Mockery::close();
}

$this->afterApplicationCreatedCallbacks = [];
$this->beforeApplicationDestroyedCallbacks = [];
}

这甚至适用于内存数据库,速度快 100 倍。

PS:为 Laravel 而不是 Lumen 应用程序工作。

关于php - 在套件中的每个测试之前运行设置代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41191460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com