foundry: Question/Problem: Error on using foundry with service injection

In my project (Symfony: 7.2), I have created a factory class that receives an interface in the constructor. The interface is instantiated and passed by using dependency injection.

In a test, I call the factory and want to create a user. Before the user is created, the following error is thrown:

LogicException: Factories with dependencies (services) cannot be created before foundry is booted.

Caused by
ArgumentCountError: Too few arguments to function App\Factory\UserFactory::__construct(), 0 passed in /path/to/vendor/zenstruck/foundry/src/Factory.php on line 47 and exactly 1 expected

The UserFactory class starts as follows:

final class UserFactory extends PersistentProxyObjectFactory {

  private UserPasswordHasherInterface $passwordHasher;

  public function __construct(UserPasswordHasherInterface $passwordHasher) {
    parent::__construct();
    $this->passwordHasher = $passwordHasher;
  }
...

Here is a part of the TestClass:

class UserServiceTest extends TestCase {

  #[Test]
  public function checkFindUserByOptInToken(): void {
    $token = 'f943852c-19bf-30c7-8f7c-b497183faa59';
    $user = UserFactory::new()
                       ->withToken($token, TokenCategory::EMAIL_CONFIRMATION)
                       ->withoutPersisting()->create()->_real();
  }
...

The output of console debug:container UserFactory returns the following:

Information for Service "App\Factory\UserFactory"
=================================================

 ---------------- -------------------------
  Option           Value
 ---------------- -------------------------
  Service ID       App\Factory\UserFactory
  Class            App\Factory\UserFactory
  Tags             foundry.factory
  Public           no
  Synthetic        no
  Lazy             no
  Shared           yes
  Abstract         no
  Autowired        yes
  Autoconfigured   yes
  Usages           none
 ---------------- -------------------------

The same command in the test environment:

Information for Service "App\Factory\UserFactory"
=================================================

 ---------------- -------------------------------
  Option           Value
 ---------------- -------------------------------
  Service ID       App\Factory\UserFactory
  Class            App\Factory\UserFactory
  Tags             foundry.factory
  Public           no
  Synthetic        no
  Lazy             no
  Shared           yes
  Abstract         no
  Autowired        yes
  Autoconfigured   yes
  Usages           test.private_services_locator
 ---------------- -------------------------------

If I run all tests of the project, it works. But when I execute the single test (./vendor/bin/phpunit tests/Service/User/UserServiceTest.php), then I get the error above. Do you have any ideas for solving the problem?

I’m using zenstruck/foundry in version 2.3.5

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 15 (9 by maintainers)

Most upvoted comments

Hi!

you should absolutely not use new Factory(). I was thinking it was marked as @internal but I see it is not, I’ll fix this in a future fix. In order to create factories, you should use YourFactory::new().

but I don’t understand why you want to use a password hasher in your unit test?

given the example in the doc, you can adapt it this way in order to work properly in unit tests:

final class UserFactory extends PersistentProxyObjectFactory
{
    public function __construct(private UserPasswordHasherInterface|null $passwordHasher = null)
    {
        parent::__construct();
    }

    public static function class(): string
    {
        return UserForPersistentFactory::class;
    }

    protected function defaults(): array
    {
        return [
            'email' => self::faker()->unique()->safeEmail(),
            'password' => '1234',
        ];
    }

    protected function initialize(): static
    {
        return $this
            ->afterInstantiate(function(UserForPersistentFactory $user) {
                if ($this->passwordHasher !== null) {
                    $user->setPassword($this->passwordHasher->hashPassword($user, $user->getPassword()));
                }
            })
        ;
    }
}

Hi!

“service” factory cannot be used in unit tests (the ones with TestCase), but only in function/integration tests (using KernelTestCase or WebTestCase).

In unit test, the container is not initialized, and you cannot use DI - I’ll add a note about it in the docs