lundi 5 octobre 2020

Custom proxy entities for fixture generation

So my question is very specific but I couldn't figure out how to make it even after several months of reflection. The following topic will be about Symfony, Doctrine and generating fixtures on-the-go for the tests.

I want to generate fixtures on the go from a test. The goal is to provide a very specific set of fixtures for each tests using helpers without sacrify the readability. That is the goal, so my idea was to create a tests/Resources/EntityProxy which is a mirror of the src/Entity folder, containing the same amount of classes with the exact same name. Each EntityProxy extends from its related Entity, use a custom trait to fill the properties easily.

You guessed it, I want to only use in tests the EntityProxy and use it directly into the functions to tests them. And there is a major issue with that, as Doctrine doesn't recognize the EntityProxy as an entity even if it extends from a real Entity.

Is there a way to say to Doctrine to persist an EntityProxy as its extended Entity?

__

The following code is an example of what I want as en EntityProxy:

namespace Tests\Resources\EntityProxy;

class User extends App\Entity\User
{
    use FixtureGenerationTrait;

    public function static makeDefault(): self
    {
        return static::generate([
           'username' => self::getFaker()->username,
           'email'    => self::getFaker()->email,
           ...
        ]);
    }

    public function static make(array $data = []): self
    {
        $entity = static::makeDefault();
        $entity = static::setValues($entity, $data);

        return $entity;
    }
}

And can be used in the tests like following: User::make(['name' => 'John Wick']);

Aucun commentaire:

Enregistrer un commentaire