Symfony 5 - PhpUnit - Database not refresh on running test

一个人想着一个人 提交于 2021-02-10 07:01:21

问题


I noticed that when I run a functional test with PhpUnit, if there is a modification in the database, it is done. However, if I'm in the middle of my test and want to recover the record that was changed, it comes back to me in its old version, which is very problematic.

For example, if I have a test in which:

  1. I collect a certain item
  2. I activate it (therefore, modification in the database of its enable property) via a URL of a controller
  3. I want to check that it is active
  4. I retrieve it from the database again
  5. I check that it is active

Well, that'll return my old item to me, and tell me it's not active.

Which forces me to create a second test to retrieve it and then check that it is active

    public function testEnableArticle()
    {
        $article = $this->getLastArticle(); //Find last article
        $admin = $this->getAdmin();
        
        $this->client->loginUser($admin);
        
        // Request to enable last article
        $this->client->request('GET', sprintf("/admin/articles/%s/enable", $article->getId()));
        
        // Now my article should be enabled :
            $updatedArticle = $this->getLastArticle();
            $this->assertSame(1, $updatedArticle->getEnable());
        // But return false because here my article seems to be the previous version before enable
    }
   

So I need a second test just after to get updated article:

    public function testLastArticleIsEnabled()
    {
        $updatedArticle = $this->getLastArticle();
        $this->assertSame(1, $updatedArticle->getEnable());
        
        // And here, it works
    }

To get my last article, I'm using my custom function :

    public function getLastArticle()
    {
        return $this->manager->getRepository(Article::class)->findLastArticle();
    }

It's very weird... Can someone help me please ?


回答1:


It's doctrine behaviour, it keeps your entity on memory once you've fetched it. It won't fetch it again from database, so you have one and only one instance. Try to:

$this->client->request('GET', sprintf("/admin/articles/%s/enable", $article->getId()));
$this->em->refresh(article);


来源:https://stackoverflow.com/questions/63226933/symfony-5-phpunit-database-not-refresh-on-running-test

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