Search code examples
doctrinephpunitsymfony-4.4

Symfony4 doctrine unit tests: entity has old data in cache?


I am developing a Symfony4 App and want to test if a service really updates my database.

Here I give in a data transfer object

public function update(ChargeDto $chargeDto): ChargeDto
{
    $charge = $this->chargeRepository->find($chargeDto->id);
    // The mapper fills the new data into my entity
    $charge = ChargeMapper::fromDto($charge, $chargeDto);
    // here I check that the entity has in fact the new data 
    VarDumper::dump($charge->getAuthorPNumber());

    $this->entityManager->persist($charge);
    $this->entityManager->flush();
    $this->entityManager->refresh($charge);
    // here I check that the entity still has the new data 
    VarDumper::dump($charge->getAuthorPNumber());

    return ChargeMapper::toDto($charge, $chargeDto);
}

In my test class I the fetch the updated dataset from the db to check if it was really really updated:

    $res = $this->chargeRepo->find($updatedDto->id);
    VarDumper::dump($res->getAuthorPNumber());

and I get the old data. If I look into the database manually I see, it was in fact updated and contains the new values.

I am not aware that any caching is actively activated. How can my test get the real fresh new and updated values?

P.S.: I just double checked: For prod environment I have a configuration for doctrine caching ( /config/prod/doctrine.yaml ) , but neither for the dev nor test environment.


Solution

  • Your entityManager should have a function called clear which will remove the cached objects. (Make sure you call this in the test only and not in the actual code)

    You can also clear only 1 type of entity from the cache by passing the EntityName as parameter to the function.