Skip to content

Instantly share code, notes, and snippets.

@lsmith77
Last active July 27, 2023 19:12
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lsmith77/9a152d4a563c8fe527643cf78e32c57d to your computer and use it in GitHub Desktop.
Save lsmith77/9a152d4a563c8fe527643cf78e32c57d to your computer and use it in GitHub Desktop.
PHPUnit functional test to check if migrations inside a Symfony app
<?php
namespace AppBundle\Tests;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\DBAL\Driver\PDOMysql\Driver as MySQLDriver;
class DoctrineMigrationTest extends WebTestCase
{
protected function setUp()
{
// Since I use LiipFunctionalTestBundle I usually use SQLite for my functional tests
// so I setup a 2nd environment for testing the Migrations with the actual target DB.
// Note this environment uses a dedicated schema (ie. my_db vs my_db_test)
$this->environment = 'mysql_test';
/* @var \Doctrine\ORM\EntityManager */
$em = $this->getContainer()->get('doctrine')->getManager();
/** @var Connection $connection */
$connection = $em->getConnection();
$driver = $connection->getDriver();
if (!$driver instanceof MySQLDriver) {
$this->markTestSkipped('This test requires MySQL.');
}
try {
$databaseName = $this->getContainer()->getParameter('database_name');
if (in_array($databaseName, $connection->getSchemaManager()->listDatabases())) {
$schemaTool = new SchemaTool($em);
// Drop all tables, so we can test on a clean DB
$schemaTool->dropDatabase();
}
} catch (\Exception $e) {
$this->fail('Could not cleanup test database for migration test: ' . $e->getMessage());
}
}
/**
* @group mysql
*/
public function testMigrations()
{
// Test if all migrations run through
$output = $this->runCommand('doctrine:migrations:migrate', ['--no-interaction']);
$this->assertRegExp('/\d+ sql queries\n$/', $output);
// Validate that the mapping files are correct and in sync with the database.
$output = $this->runCommand('doctrine:schema:validate');
$this->assertContains('[Mapping] OK - The mapping files are correct.', $output);
$this->assertContains('[Database] OK - The database schema is in sync with the mapping files.', $output);
}
}
@lsmith77
Copy link
Author

# config_mysql_test.yml
parameters:
    database_name: '%env(MYSQL_TEST_DATABASE)%'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment