Load All Fixtures when one has a constructor parameter

Viewed 113

I would know how is possible to load all fixtures when one of them contain a constructor parameter.

For now, I use this method to load all fixtures :

/**
* @return string[]
* @codeCoverageIgnore
* load all fixtures in the good order regarding relations
*/

// Names are samples
public function getDependencies()
{
  return [
           UserFixture::class,
           AAAFixture::class,
           BBBFixture::class,
           CCCFixture::class,
           DDDFixture::class,
           EEEFixture::class,
           FFFFixture::class,
           GGGFixture::class
       ];
}

It works good when I use the symfony command :

php bin/console doctrine:fixtures:load --env=test

In my test code I can load fixtures with this methods

public function addFixture(FixtureInterface $fixture): void
{
   $this->getFixtureLoader()->addFixture($fixture);
}


public function executeFixtures(): void
{
   $this->getFixtureExecutor()->execute($this->fixtureLoader->getFixtures());
}


private function getFixtureExecutor()
{
   if (!$this->fixtureExecutor) {
     $entityManager = static::getContainer()->get('doctrine')->getManager();
     $this->fixtureExecutor = new ORMExecutor($entityManager, new 
     ORMPurger($entityManager));
   }

 return $this->fixtureExecutor;
}


private function getFixtureLoader()
{
   if (!$this->fixtureLoader) {
      $this->fixtureLoader = new ContainerAwareLoader(static::getContainer());
   }

   return $this->fixtureLoader;
}

And into my tests files :

self::$fixtureService->addFixture(new UserFixture($hasher));
self::$fixtureService->addFixture(new BBBFixture());
self::$fixtureService->executeFixtures();

But I would do this :

self::$fixtureService->addFixture(new AllFixture());
self::$fixtureService->executeFixtures();

But when I do this, an error is generated because UserFixture need the hasher password interface.

// UserFixture.php //

private UserPasswordHasherInterface $hasher;

/**
* UserFixture constructor.
* @param UserPasswordHasherInterface $hasher
* @codeCoverageIgnore
*/
public function __construct(UserPasswordHasherInterface $hasher)
{
  $this->hasher = $hasher;
}

I wouldn't do this :

self::$fixtureService->addFixture(new UserFixture($hasher));
self::$fixtureService->addFixture(new AllFixture()); // without userFixture in it

self::$fixtureService->executeFixtures();

Can someone tell me how I can solve this ?

1 Answers

Then you need dependency injection. Inject UserFixture to the class or method where you want to use it, and if UserPasswordHasherInterface resolves to a real service (check config), the fixture will be instantiated.

Side note: It's better to separate mandatory and test data fixtures (two namespaces, separate logic). One supplying the data required to run the application in production, and the latter supplying data required to run tests only.

Related