Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with the Entity Manager and phpunit in Symfony 2

I have an issue with my Entity Manager in phpunit.

This is my test :

public function testValidChangeEmail()
{
    $client = self::createAuthClient('user','password');

    $crawler = $client->request('GET', '/user/edit/30');
    $crawler = $client->submit($crawler->selectButton('submit')->form(array(
        'form[email]' => '[email protected]',
    )));

    /*
     * With this em, this work perfectly 
     * $em = $client->getContainer()->get('doctrine.orm.entity_manager');
     */

    $user = self::$em->getRepository('MyBundle:User')->findUser('[email protected]');

    die(var_dump($user->getEmail()));
}

and this is my WebTestCase which extends original WebTestCase :

class WebTestCase extends BaseWebTestCase
{
    static protected $container;
    static protected $em;

    static protected function createClient(array $options = array(), array $server = array())
    {
        $client = parent::createClient($options, $server);
        self::$em = $client->getContainer()->get('doctrine.orm.entity_manager');
        self::$container = $client->getContainer();

        return $client;
    }

    protected function createAuthClient($user, $pass)
    {
        return self::createClient(array(), array(
            'PHP_AUTH_USER' => $user,
            'PHP_AUTH_PW'   => $pass,
        ));
    }

As you can see, I replace the self::$em when I created my client.

My issue :

In my test, the die() give me the old email and not the new email ([email protected]) which has registered in the test. However in my database, I have the [email protected] correctly saved.

When I retrieve my user in the database, I use sefl::$em. If I use the $em in comments, I retrieve the right new email.

I don't understand why in my WebTestCase, I can access to the new Entity Manager...

like image 713
rgazelot Avatar asked Oct 06 '22 09:10

rgazelot


1 Answers

You can't access to the new entity manager because Symfony's client class shutdown's kernel before each request, which means that it erase whole service container and build it again from scratch.

So, after SECOND request you get very different entity manager than one you have in your own WebTestCase class. (I said after second because client shutdown's kernel only if any request has been already performed)

The question is - do you really need the same entity manafer in your WebTestCase class? Actually, you may want use the same entity manager because you want let say get controll over transaction between requests. But in this case you should create your own test client class extended symfony's one and there define static connection or entity manager, and put it into container before every request.

Look at example: http://alexandre-salome.fr/blog/Symfony2-Isolation-Of-Tests

like image 153
Cyprian Avatar answered Oct 10 '22 04:10

Cyprian