Skip to content

Instantly share code, notes, and snippets.

@tinker1987
Last active September 1, 2017 14:00
Show Gist options
  • Select an option

  • Save tinker1987/bdc62bbc4c4d57f4fba3eef5c31f805a to your computer and use it in GitHub Desktop.

Select an option

Save tinker1987/bdc62bbc4c4d57f4fba3eef5c31f805a to your computer and use it in GitHub Desktop.
Allow to load fixtures for integration tests
<?php
declare(strict_types=1);
namespace Tests;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader;
/**
* Class FixtureAwareTestCaseTrait
* @package Tests
* @author Dmytro Paiareli <[email protected]>
*/
trait FixtureAwareTestCaseTrait
{
/**
* @var ORMExecutor
*/
private $fixtureExecutor;
/**
* @var ContainerAwareLoader
*/
private $fixtureLoader;
/**
* Adds a new fixture to be loaded.
* @param FixtureInterface $fixture
* @return self
*/
protected function addFixture(FixtureInterface $fixture)
{
$this->getFixtureLoader()->addFixture($fixture);
return $this;
}
/**
* 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;
}
}
@tinker1987
Copy link
Author

tinker1987 commented Aug 24, 2017

Test case class should extends Symfony\Bundle\FrameworkBundle\Test\KernelTestCase to able get access to service container.

class FooTest extends Symfony\Bundle\FrameworkBundle\Test\KernelTestCase
{
    use Tests\FixtureAwareTestCaseTrait;

    public function setUp()
    {
        self::bootKernel();

        // Base fixture for all tests
        $this
                ->addFixture(new FirstFixture())
                ->addFixture(new SecondFixture())
                ->executeFixtures();

        // Fixtures are now loaded in a clean DB
    }
}

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