mergeManager = $this->getContainer()->get(ThirdpartyMergeService::class); $this->em = $this->getContainer()->get(EntityManagerInterface::class); $this->connection = $this->em->getConnection(); // Start a transaction before each test $this->connection->beginTransaction(); } protected function tearDown(): void { try { // Rollback the transaction after each test to ensure no data is persisted $this->connection->rollBack(); } catch (\Exception) { $this->connection->close(); } parent::tearDown(); } public function testThirdpartyMerge(): void { // Arrange: Create Thirdparty entities $toKeep = new ThirdParty(); $toKeep->setName('Thirdparty ToKeep'); $toKeep->setEmail('keep@example.com'); $toDelete = new ThirdParty(); $toDelete->setName('Thirdparty ToDelete'); // This should be ignored $toDelete->setTelephone(new PhoneNumber('123456789')); // Related entities $activity = new Activity(); $activity->addThirdParty($toDelete); // This is a Many-to-Many relation $personResource = new PersonResource(); $personResource->setThirdParty($toDelete); // This is a Many-to-One relation $this->em->persist($toKeep); $this->em->persist($toDelete); $this->em->persist($activity); $this->em->persist($personResource); $this->em->flush(); // Merge $this->mergeManager->merge($toKeep, $toDelete); $this->em->clear(); // Verify data was merged correctly $mergedThirdparty = $this->em->getRepository(ThirdParty::class)->find($toKeep->getId()); $this->assertNotNull($mergedThirdparty); $this->assertEquals('Primary Name', $mergedThirdparty->getName(), 'Name should remain unchanged'); $this->assertEquals('keep@example.com', $mergedThirdparty->getEmail(), 'Email should remain unchanged'); $this->assertEquals('123456789', $mergedThirdparty->getPhone(), 'Phone should be transferred from Thirdparty ToDelete'); // Check that relationships are updated $updatedActivity = $this->em->getRepository(Activity::class)->find($activity->getId()); $this->assertTrue( $updatedActivity->getThirdParties()->contains($mergedThirdparty), 'Activity should be linked to the merged Thirdparty' ); $this->assertFalse( $updatedActivity->getThirdParties()->exists(fn ($key, $tp) => $tp->getId() === $toDelete->getId()), 'Activity should no longer reference the deleted Thirdparty' ); $updatedPersonResource = $this->em->getRepository(PersonResource::class)->find($personResource->getId()); $this->assertEquals( $mergedThirdparty->getId(), $updatedPersonResource->getThirdParty()->getId(), 'PersonResource should reference the merged Thirdparty' ); // Ensure the 'toDelete' entity is removed $deletedThirdparty = $this->em->getRepository(ThirdParty::class)->find($toDelete->getId()); $this->assertNull($deletedThirdparty, 'The deleted Thirdparty should no longer exist in the database'); } }