【Symfony2】DoctrineFixturesBundle で作ったフィクスチャを phpunit から呼びたいとき
機能テストをするときにテストデータを DoctrineFixturesBunle で作った LoadHogeData クラスを使いたいとき
- LoadHogeDataクラスが ContainerAwareInterface を実装しているときどうするか
- LoadHogeData が外部キー制約で怒られるときはどうするか
について書きます。
ほとんど以下の「テストコードからFixtureをロードする」項目からのコピペです。
こうしました。泥臭さが出るけど致し方ない。
- LoadHogeDataクラスが ContainerAwareInterface を実装しているときどうするか fixture に自分で Container をセットする。
- LoadHogeData が外部キー制約で怒られるときはどうするか SET FOREIGN_KEY_CHECKS = 0 を無理やり叩いて外部キー制約を無効化する。
use AppBundle\DataFixtures\ORM\LoadHogeData; use Doctrine\Common\DataFixtures\Loader; use Doctrine\ORM\EntityManager; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\Purger\ORMPurger; use Symfony\Component\DependencyInjection\ContainerInterface; class HogeFuntionalTest extends WebTestCase { /** * @var EntityManager; */ private $em; /** * @var ContainerInterface; */ private $container; public function setUp() { # kernel のブート { $kernel = static::createKernel(); $kernel->boot(); # } # EntityManager の取得 { $this->container = $kernel->getContainer(); $this->em = $this->container->get('doctrine.orm.entity_manager'); # } # 外部キー制約の無効化 { $connection = $this->em->getConnection(); $connection->exec('SET FOREIGN_KEY_CHECKS = 0'); # } # フィクスチャの実行 { $loader = new Loader($this->container); $fixture = new LoadAccountantData(); $fixture->setContainer($this->container); # ContainerAwareInterface を実装している場合インスタンス化してから自分で container をセットする必要がある $loader->addFixture($fixture); $fixtures = $loader->getFixtures(); $purger = new ORMPurger($this->em); $purger->setPurgeMode(ORMPurger::PURGE_MODE_TRUNCATE); $executor = new ORMExecutor($this->em, $purger); $executor->execute($fixtures); # } # 外部キー制約の有効化 { $connection->exec('SET FOREIGN_KEY_CHECKS = 1'); # } } …
外部キー制約で php app/console doctrine:fixtures:load
がたたけ無いときはこっち