How to setup a Doctrine test to have automatic rollback of the transaction (to avoid dirtying db)?

1.6k Views Asked by At

I would like to have tests dealing with Doctrine not persist stuff in the main Symfony dev database. Preferably by not storing stuff at all (rolling back per test). How would I do this? Are there ready-made frameworks/libs/setups I can use?

At work we have a really smooth working Java setup where database tests extends custom JUnit test classes we have created. TransactionallyIsolatedITest for running everything within a transaction that is rolled back (fast), FullyIsolatedITest for testing stuff that do their own begin(), commit(), stuff, etc. This creates and tears down a database created from a template for each test (heavy/slow).

Having something like this would be beautful when doing Symfony development in PHP.

2

There are 2 best solutions below

0
oligofren On BEST ANSWER

In the Symfony 6 documentation they actually describe and show how to reset the database before every test using the DAMADoctrineTestBundle.

2
Beri On

You could try overriding the setUp method, inside that you can get the enityManager instance like this $em = self::getContainer()->get('doctrine')->getManager(); and then purge the database via the Doctrine ORM purger

$purger = new Doctrine\Common\DataFixtures\Purger\ORMPurger($em);
$purger->purge();