I'm actually doing some functionnal testing on my api and I'm facing a problem which I don't really understand.
I want to test an API which interact with a remote web hosting server. The goal is to manage VirtualHosts, DNS zones, database etc...
I have a test remote server and to avoid conflicts, I remove the created stuff after the test (in the TearDown() function) and create the base (in the setUp() function). In the setUp() I also load fixtures in the setup.
After a test which add a child of my main entity, I want to clean the remote server :
$service = $this->fixtures->getReference('service-web');
$this->container->get('webmanager')->deleteHosting($service, true);
The deleteHosting() function deletes all remote stuff (the true parameter is the "force" parameter, which ensure that the function doesn't stop after an error.
The $service variable contains my main service entity. I also have in this entity a One-To-Many relationship with addonDomain's entity.
My functionnal test creates an addonDomain.
The test is OK, but when I try to delete my service, the attached entity makes Doctrine yell as hell : Doctrine\ORM\ORMInvalidArgumentException: Detached entity AppBundle\Entity\Service\Web\AddonDomain@0000000054814da900000000073c524a cannot be removed.
I tried a lot of things but none of them works (ie : using the doctrine manager to retrieve the entity instead of using the fixture.
Thanks a lot for your help, best regards.
SOLVED ! In fact, I'm using the container and the entity manager of the test class and not of the client himself. That was the problem...
Although this is an old question, I had the same problem recently while working with Symfony 4.4 and Detached entity error in Doctrine helped me solve the problem. Basically, as @Can Vural suggested, calling merge before remove is solving the problem, but the missing bit is that you have to assign the entity again so:
$entity = $doctrineManager->merge($detachedEntity);
$doctrineManager->remove($entity);
$doctrineManager->flush();
This solved my problem.
Please keep in mind that merge is deprecated and will be removed in Doctrine 3: https://github.com/doctrine/orm/blob/master/UPGRADE.md#bc-break-removed-entitymanagermerge-and-entitymanagerdetach-methods
Ive came accross the same problem and merge did not solve it for me in functional test so instead I am querying the entities again and then remove them:
class ControllerTest extends WebTestCase {
public function testCanGet() {
$em = static::getContainer()->get(EntitiyManagerInterface::class);
$entity = new Entity();
$em->persist($entity);
$em->flush();
$client = static::createClient();
$client->request("GET", "/route");
$this->assertResponseIsSuccessful();
// Remove entity
$em->remove($em->getRepository(Entity::class)->find($entity->getId()));
$em->flush();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With