Issue with the Entity Manager and phpunit in Symfony 2

Posted by rgazelot on Stack Overflow See other posts from Stack Overflow or by rgazelot
Published on 2012-10-10T15:29:00Z Indexed on 2012/10/10 15:37 UTC
Read the original article Hit count: 286

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...

© Stack Overflow or respective owner

Related posts about symfony2

Related posts about doctrine2