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