问题
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:
- I collect a certain item
- I activate it (therefore, modification in the database of its enable property) via a URL of a controller
- I want to check that it is active
- I retrieve it from the database again
- 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