Skip to content

Instantly share code, notes, and snippets.

@coudenysj
Created November 21, 2012 10:58
Show Gist options
  • Save coudenysj/4124299 to your computer and use it in GitHub Desktop.
Save coudenysj/4124299 to your computer and use it in GitHub Desktop.
Using multiple databases in phpunit/dbunit with composer
{
"repositories": [
{
"type": "package",
"package": {
"name": "hamcrest/hamcrest",
"version": "1.1.0",
"dist": {
"type": "zip",
"url": "https://hamcrest.googlecode.com/files/hamcrest-php-1.1.0.zip"
},
"include-path": ["Hamcrest-1.1.0/"],
"autoload": {
"psr-0": { "Hamcrest_": "Hamcrest-1.1.0/" },
"files": ["Hamcrest-1.1.0/Hamcrest/Hamcrest.php"]
}
}
},
{
"type": "package",
"package": {
"name": "etsy/phpunit-extensions",
"version": "0.6.0",
"dist": {
"type": "zip",
"url": "https://github.com/etsy/phpunit-extensions/archive/v0.6.0.zip"
},
"autoload": {
"psr-0": { "PHPUnit_": "" }
}
}
}
],
"require": {
"php": ">=5.3.2"
},
"require-dev": {
"hamcrest/hamcrest": "1.1.0",
"mockery/mockery": ">=0.7.2",
"etsy/phpunit-extensions": "0.6.0",
"phpunit/phpunit": "3.7.*",
"phpunit/dbunit": "1.2.*"
},
"include-path": ["vendor/mockery/mockery/library"]
}
/**
* Specific example for Zend Framework 1.0 applications (update the database "fetching")
*/
class DatabaseTest extends PHPUnit_Extensions_MultipleDatabase_TestCase
{
protected function getDatabaseConfigs()
{
$configs = array();
$options = $this->_application->getOptions();
$databases = $options['resources']['dbs'];
foreach ($databases as $database) {
$fixture = __DIR__ . '/_files/fixture_' . $database . '.xml';
if (is_file($fixture)) {
$tables = simplexml_load_file($fixture);
if (count($tables) == 0) {
// don't register databases with empty fixtures
continue;
}
unset($tables);
$builder = new PHPUnit_Extensions_MultipleDatabase_DatabaseConfig_Builder();
$builder->connection(
new PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection(
$this->_application->getBootstrap()
->getPluginResource('Dbs')
->getDbAdapter($database)
->getConnection(),
$database
)
);
$builder->dataSet(
new PHPUnit_Extensions_Database_DataSet_XmlDataSet($fixture)
);
$configs[$database] = $builder->build();
}
}
return $configs;
}
/**
* Fetch a specific connection to do testing (rowcount, etc...)
*
* @param string $database The name of the database
*
* @return PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection
*/
public function getConnection($database)
{
$configs = $this->getDatabaseConfigs();
return $configs[$database]->getConnection();
}
}
cd $PROJECT_ROOT
curl -s https://getcomposer.org/installer | php
php composer.phar install --dev
vendor/bin/phpunit --version
$this->assertEquals(0, $this->getConnection('dbname')->getRowCount('user'), "Pre-Condition");
$user = new User();
$user->save();
$this->assertEquals(1, $this->getConnection('dbname')->getRowCount('user'), "Inserting failed");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment