9

I have an application built on Symfony2 + Doctrine2 which I want to create some tests for (using phpunit).

For example if I want to test a unique validator against a record in the DB, I want to create a record I can work with, but after the test I don't need it anymore. So is there a way to create temporary (or virtual) fixtures or do I have to manually create and delete them?

tamir
  • 3,207
  • 2
  • 33
  • 51

1 Answers1

21

You can use Doctrine DataFixture and put this code in your setUp method of a unit test class:

$loader = new Doctrine\Common\DataFixtures\Loader;
$loader->loadFromDirectory('/path/to/MyDataFixtures');
$purger = new Doctrine\Common\DataFixtures\Purger\ORMPurger($em);
$executor = new Doctrine\Common\DataFixtures\Executor\ORMExecutor($em, $purger);
$executor->execute($loader->getFixtures());

You can refer to the docs to see how create DataFixture classes.

Here is a good example of how to do it: Symfony 2 + Doctrine 2 + PHPUnit 3.5: Serialization of closure exception

PS: I assume you have a working $em (EntityManager) in this example.

Community
  • 1
  • 1
Florian Klein
  • 8,692
  • 1
  • 32
  • 42
  • 2
    Or, $loader = new \Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader(static::$kernel->getContainer()); If you need to use a fixture that implements ContainerAwareInterface. Also, thanks! Just used this answer. – skqr Apr 28 '13 at 22:24
  • 1
    Does the PRMPurger really require an $em for it's initiation? – Tjorriemorrie Feb 04 '14 at 12:45
  • what's the best way to load all fixtures from src directories? – Serge Velikan Oct 02 '15 at 17:02