Last active
October 7, 2020 12:27
-
-
Save Vp3n/5472509 to your computer and use it in GitHub Desktop.
Symfony2 helper class to handle EntityManager transaction between tests.
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 | |
namespace MyBundle\TestBundle\Lib; | |
use Doctrine\ORM\EntityManager; | |
use \Symfony\Bundle\FrameworkBundle\Test\WebTestCase; | |
/** | |
* Helper class to help manager transaction for each test, | |
* database needs to be initialized once before whole test suite | |
*/ | |
abstract class DatabaseWebTest extends WebTestCase { | |
/** | |
* helper to acccess EntityManager | |
*/ | |
protected $em; | |
/** | |
* Helper to access test Client | |
*/ | |
protected $client; | |
/** | |
* Before each test we start a new transaction | |
* everything done in the test will be canceled ensuring isolation et speed | |
*/ | |
protected function setUp() | |
{ | |
parent::setUp(); | |
$this->client = $this->createClient(); | |
$this->em = static::$kernel->getContainer() | |
->get('doctrine') | |
->getManager(); | |
$this->em->beginTransaction(); | |
} | |
/** | |
* After each test, a rollback reset the state of | |
* the database | |
*/ | |
protected function tearDown() | |
{ | |
parent::tearDown(); | |
$this->em->rollback(); | |
$this->em->close(); | |
} | |
} |
Also I suggest adding a way to catch exceptions in tearDown such as if no transaction is detected, you avoid a fatal error. Like this:
protected function tearDown()
{
parent::tearDown();
try {
$this->em->rollback();
$this->em->close();
} catch(\Exception $e) {
echo 'No transactions to rollback to' . $e->getMessage();
}
}
I would recommend to use this instead 😉
https://github.com/dmaicher/doctrine-test-bundle
It will also work for WebTestCase
when performing functional tests.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks !