Skip to content

Instantly share code, notes, and snippets.

@Vp3n
Last active October 7, 2020 12:27
Show Gist options
  • Save Vp3n/5472509 to your computer and use it in GitHub Desktop.
Save Vp3n/5472509 to your computer and use it in GitHub Desktop.
Symfony2 helper class to handle EntityManager transaction between tests.
<?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();
}
}
@Renrhaf
Copy link

Renrhaf commented Jan 22, 2014

thanks !

@EtienneDh
Copy link

Thanks, really useful, was lazy to do it myself and i'm glad someone did it in the first place :) you should add @author and @link tags to your class !

@EtienneDh
Copy link

EtienneDh commented Feb 17, 2017

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();    
 }

}

@dmaicher
Copy link

dmaicher commented Mar 3, 2017

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