Issue with the Entity Manager and phpunit in Symfony 2

戏子无情 提交于 2019-12-23 10:05:59

问题


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]' => 'new@email.com',
    )));

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

    $user = self::$em->getRepository('MyBundle:User')->findUser('new@email.com');

    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 (new@email.com) which has registered in the test. However in my database, I have the new@email.com 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...


回答1:


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



来源:https://stackoverflow.com/questions/12823021/issue-with-the-entity-manager-and-phpunit-in-symfony-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!