Created
May 2, 2016 12:23
-
-
Save a-ast/c07a2456fcb4bf4f7a947bff40c25366 to your computer and use it in GitHub Desktop.
Load doctrine fixtures before test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Doctrine\Common\DataFixtures\Executor\ORMExecutor; | |
use Doctrine\Common\DataFixtures\FixtureInterface; | |
use Doctrine\Common\DataFixtures\Purger\ORMPurger; | |
use Doctrine\ORM\EntityManagerInterface; | |
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader; | |
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; | |
abstract class FixtureAwareTestCase extends KernelTestCase | |
{ | |
/** | |
* @var ORMExecutor | |
*/ | |
private $fixtureExecutor; | |
/** | |
* @var ContainerAwareLoader | |
*/ | |
private $fixtureLoader; | |
public function setUp() | |
{ | |
self::bootKernel(); | |
} | |
/** | |
* Adds a new fixture to be loaded. | |
* | |
* @param FixtureInterface $fixture | |
*/ | |
protected function addFixture(FixtureInterface $fixture) | |
{ | |
$this->getFixtureLoader()->addFixture($fixture); | |
} | |
/** | |
* Executes all the fixtures that have been loaded so far. | |
*/ | |
protected function executeFixtures() | |
{ | |
$this->getFixtureExecutor()->execute($this->getFixtureLoader()->getFixtures()); | |
} | |
/** | |
* @return ORMExecutor | |
*/ | |
private function getFixtureExecutor() | |
{ | |
if (!$this->fixtureExecutor) { | |
/** @var \Doctrine\ORM\EntityManager $entityManager */ | |
$entityManager = self::$kernel->getContainer()->get('doctrine')->getManager(); | |
$this->fixtureExecutor = new ORMExecutor($entityManager, new ORMPurger($entityManager)); | |
} | |
return $this->fixtureExecutor; | |
} | |
/** | |
* @return ContainerAwareLoader | |
*/ | |
private function getFixtureLoader() | |
{ | |
if (!$this->fixtureLoader) { | |
$this->fixtureLoader = new ContainerAwareLoader(self::$kernel->getContainer()); | |
} | |
return $this->fixtureLoader; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MyTestCase extends FixtureAwareTestCase | |
{ | |
public function setUp() | |
{ | |
parent::setUp(); | |
// Base fixture for all tests | |
$this->addFixture(new FirstFixture()); | |
$this->addFixture(new SecondFixture()); | |
$this->executeFixtures(); | |
// Fixtures are now loaded in a clean DB. Yay! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment