使用 Codeception ,你可以为任何你想要的东西创建一个助手,包括迁移加载。
这是在每次测试之前加载数据库迁移的助手。我没有机会测试这段代码,但这里的主要思想应该很清楚。
代码接收助手:
namespace Codeception\Module;
use Codeception\Module;
use Codeception\TestInterface;
use Phinx\Console\PhinxApplication;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\NullOutput;
class FixtureHelper extends Module
{
/**
* Run database migrations before each test if database population enabled.
*
* @param TestInterface $test
*/
public function _before(TestInterface $test)
{
$populate = $this->getModule('Db')->_getConfig('populate');
if ($populate) {
$this->migrateDatabase();
}
}
/**
* Run the database migrations.
*/
public function migrateDatabase()
{
// Run Phinx console application.
$app = new PhinxApplication();
$app->setAutoExit(false);
$output = new NullOutput();
//$output = new ConsoleOutput();
// Run database migrations for test environment.
$input = new StringInput('migrate -e test');
$app->run($input, $output);
// ... you also can load the fixtures here
//$input = new StringInput('seed:run -s <my-seeds> -e test');
//$app->run($input, $output);
}
}
Codeception 配置(用于功能测试):
actor: FunctionalTester
modules:
enabled:
- ... your modules
- FunctionalHelper
- FixtureHelper
config:
Db:
dsn: '... dsn'
user: '%DB_USER%'
password: '%DB_PASSWORD%'
dump: 'tests/_data/dump.sql'
populate: true
cleanup: true
FixtureHelper:
depends: Db
数据库转储(tests/_data/dump.sql):
-- Dump should not be empty because cleanup will not work.
-- So at least any silly sql query.
SELECT 1+2 AS veryComplicatedCalculations;
Phinx config ( phinx.yml
) 必须与 Codeception config () 位于同一目录中,codeception.yml
否则您必须确保PhinxApplication
加载您的配置。
希望这有帮助!