Skip to content

Instantly share code, notes, and snippets.

@micronax
Created April 7, 2014 18:34
Show Gist options
  • Save micronax/10027693 to your computer and use it in GitHub Desktop.
Save micronax/10027693 to your computer and use it in GitHub Desktop.
A simple and modular way to use Doctrines Data-Fixtures in Symfony2 Unit-Tests.
<?php
namespace Acme\CoreBundle\Tests;
use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Doctrine\Common\DataFixtures\FixtureInterface;
class AppWebTestCase extends WebTestCase
{
/** @var \Doctrine\ORM\EntityManager */
public $em;
/** @var \Symfony\Component\DependencyInjection\ContainerInterface $container */
public $container;
private $fixturesRegistry = array();
/**
* {@inheritDoc}
*/
public function setUp()
{
static::$kernel = static::createKernel();
static::$kernel->boot();
$this->container = static::$kernel->getContainer();
$this->em = $this->container
->get('doctrine')
->getManager();
$this->generateSchema();
$this->loadFixtures();
}
public function addFixture(FixtureInterface $fixture) {
$this->fixturesRegistry[] = $fixture;
}
/**
* @return null
*/
protected function generateSchema()
{
$metadatas = $this->getMetadatas();
if (!empty($metadatas)) {
$tool = new SchemaTool($this->em);
$tool->dropSchema($metadatas);
$tool->createSchema($metadatas);
}
}
/**
* @return array
*/
protected function getMetadatas()
{
return $this->em->getMetadataFactory()->getAllMetadata();
}
/**
* {@inheritDoc}
*/
protected function tearDown()
{
parent::tearDown();
$this->em->close();
}
/**
* Load fixtures from FixtureRegistry
*/
protected function loadFixtures()
{
/** @var FixtureInterface $fixture */
foreach ($this->fixturesRegistry as $fixture) {
$fixture->load($this->em);
}
}
}
# /app/config/config_test.php
# Make PHPUnit use it's own database.
doctrine:
dbal:
dbname: "%database_name%_test"
<?php
namespace Acme\CoreBundle\Tests\Service;
use Acme\CoreBundle\Tests\AppWebTestCase;
use Acme\CoreBundle\DataFixtures\LoadUsers;
use Acme\OtherBundle\DataFixtures\LoadFooBar;
class NotificationComposerTest extends AppWebTestCase
{
/**
* {@inheritDoc}
*/
public function setUp()
{
$this->addFixture(new LoadUsers());
$this->addFixture(new LoadFooBar());
parent::setUp();
}
public function testWhateverYouWant()
{
// Perform your tests here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment