I have the following problem with doctrine when testing a symfony 5 application. Instead of updating the rows in the database, new rows are created when the persist () method is called or when cascade = {“persist”} is defined in Entity. The above issue only occurs in a test environment. Everything works fine in the app itself.
sample test code (maximally simplified to show the problem)
class GetReadyArticlesTest extends FunctionalDBTest
{
protected function setUp():void
{
parent::setUp();
$this->addFixture(new ConfigurationFixtures());
$this->addFixture(new CopyWriterTextOrderFixtures());
$this->executeFixtures();
}
protected function tearDown(): void
{
parent::tearDown();
}
public function testProcessSaveArticles()
{
$textOrderRepository = $this->entityManager->getRepository(CopywriterTextOrder::class);
$textOrderEntity = $textOrderRepository->find(1);
$textOrderEntity->setCharacters(4500);
$this->entityManager->persist($textOrderEntity);
$this->entityManager->flush();
}
}
Abstract class FunctionalDBTest:
abstract class FunctionalDBTest extends FunctionalTest
{
/**
* @var EntityManagerInterface
*/
protected $entityManager;
/**
* @var ORMExecutor
*/
private $fixtureExecutor;
/**
* @var ContainerAwareLoader
*/
private $fixtureLoader;
protected function setUp(): void
{
parent::setUp();
if ($this->getContainer()->getParameter('kernel.environment') !== 'test') {
die('Wymagane środowisko testowe');
}
$this->entityManager = $this
->getContainer()
->get('doctrine')
->getManager();
$schemaTool = new SchemaTool($this->entityManager);
$schemaTool->updateSchema($this->entityManager->getMetadataFactory()->getAllMetadata());
}
protected function addFixture(FixtureInterface $fixture): void
{
$this->getFixtureLoader()->addFixture($fixture);
}
protected function executeFixtures(): void
{
$this->getFixtureExecutor()->execute($this->getFixtureLoader()->getFixtures());
}
private function getFixtureExecutor(): ORMExecutor
{
if (!$this->fixtureExecutor) {
$this->fixtureExecutor = new ORMExecutor($this->entityManager, new ORMPurger($this->entityManager));
}
return $this->fixtureExecutor;
}
private function getFixtureLoader(): ContainerAwareLoader
{
if (!$this->fixtureLoader) {
$this->fixtureLoader = new ContainerAwareLoader($this->getContainer());
}
return $this->fixtureLoader;
}
protected function tearDown(): void
{
(new SchemaTool($this->entityManager))->dropDatabase();
parent::tearDown();
$this->entityManager->close();
$this->entityManager = null;
}
}
Removing the persist () method in this example fixes the problem. But in case I want to save a new relation to the table, it also generates a new main object. the problem only occurs in tests.