2
votes

I have a problem during testing a symfony App with phpunit. I created a service and it works well but when I execute the service in my tests doctrine throw me an exception

A new entity was found through the relationship 'PointOfSale#country' that was not configured to cascade persist operations for entity

In my service I do this:

$pointOfSale->setCountry($this->getCountry($name));

private function getCountry(string $name): Country
    {
        $country = $this->entityManager->getRepository(Country::class)->findOneBy(['alpha3Code' => $name]);
        return $country;
    }

I don't understand why this entity is not managed by UnitOfWorks. Indeed when I do the following code I have an exception only during test

$country = $this->entityManager->getRepository(Country::class)->findOneBy(['alpha3Code' => $name]);
$this->entityManager->refresh($country);
 [ERROR] Entity Namespace\Country@000000001bfea0ed00000000602457d6 is not managed. An entity is    
         managed if its fetched from the database or registered as new through EntityManager#persist      

How can I fix this ?

2
Your code looks right. Do you call $this->entityManager->clear(); anywhere in your code? That will make the entity manager forget all found entities.Vyctorya
To confirm my error I did a refresh just after findOneBy and got error. So no clearal37350
You fetch the country with $this->entityManager but refresh it with $this->coreManager. It looks like coreManager is not aware of the unitOfWork of entityManager. Why are you using two managers?Vyctorya
It's the same manage (bad rename for example). After findOneBy if I do $this->entityManager->getUnitOfWork()->isInIdentityMap($country) it returns true but it returns false in testsal37350

2 Answers

0
votes

While troubleshooting the same problem with PhpUnit Testing producing "A new entity was found through the relationship" errors I realized I was actually getting different Entity Manager instances thanks to this question. What I did was move the self::bootKernel() from my __construct function to a new "startUp" function that I run at beginning of each test function and then I started getting the correct Entity Manager each time instead of a different one each test.

I may be missing something, but now my tests pass and produce the same results as my actual program.