vendredi 17 février 2017

How to rollback transactions when doing functional testing with Symfony2

I'm trying to write a functional test for my project in Symfony2. I'd like to test if a user can access a page, fill up a form and submit it. I'm tryingto find a way to rollback the database to the state it was before the test. I found a helper class I slighty modified at http://ift.tt/2m1jSSL wich extends WebTestCase and overload setUp and tearDown methods. Here are the mods I did in order to try to make it works:

 /**
 * 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->getConnection()->beginTransaction();
    $this->em->getConnection()->setAutoCommit(false);
}
/**
 * After each test, a rollback reset the state of 
 * the database
 */
protected function tearDown()
{
    parent::tearDown();
    if($this->em->getConnection()->isTransactionActive()){
        echo 'existing transactions';
        $this->em->getConnection()->rollback();
        $this->em->close();
    }
}

When I run the tests, it acknowledges for existing transactions but the rollback fails and modifications are persisted.

What am I doing wrong ? Is that even the best practice ? Any help would be appreciated :)

Aucun commentaire:

Enregistrer un commentaire