2
votes

I am building a web application using Symfony 4. I am trying to load fixtures from my functional tests. I have created a fixture class:

<?php

namespace App\DataFixtures;

use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class TestFixtures extends Fixture
{
private $encoder;

public function __construct(UserPasswordEncoderInterface $encoder)
{
    $this->encoder = $encoder;
}

public function load(ObjectManager $em)
{
    $user = new User();
    $user->setUsername('[email protected]');
    $user->setIsActive(true);
    $user->setEmail('[email protected]');
    $user->setFirstName('John');
    $user->setLastName('Doe');
    $user->setSchool($school);
    $user->setRoles(['ROLE_USER']);
    $password = $this->encoder->encodePassword($user, 'pass1234');
    $user->setPassword($password);

    $em->persist($user);
    $em->flush();

    return $user;
}

}

I have configured services_test.yaml to pass the service to the fixture:

services:
_defaults:
    public: true

App\DataFixtures\TestFixtures:
    arguments: ['@security.password_encoder']

However, when I try to run my tests I get the following error:

ArgumentCountError: Too few arguments to function App\DataFixtures\TestFixtures::__construct(), 0 passed in /Development/app/src/Test/ApiTestCase.php on line 38 and exactly 1 expected

This is the function from my test case:

protected function setUp()
{
    $this->client = self::$staticClient;
    $this->purgeDatabase();

    $em = $this->getEntityManager();
    $fixture = new TestFixtures();
    $fixture->load($em);
}

Thanks in advance for any advice offered on this...

1
It doesn't matter that you've set the TestFixture service arguments since in your test you're doing new TestFixtures, the registered service and the instance from your test are two different things. Try to retrieve the service from the container instead symfony.com/blog/new-in-symfony-4-1-simpler-service-testing stackoverflow.com/a/17798257/5988258 . Maybe tell the exact version of symfony if you can't manage to do itSebi Ilie
Thanks for your help, I am currently using Symfony 4.0 but the 4.1 version looks like it could be very helpful in this scenario so I will look into upgrading.Shaun

1 Answers

3
votes

You are instantiating a class: $fixture = new TestFixtures(); whereas you need it as a service. You need to either, do this $fixture = new TestFixtures(encoder); where encoder is either an instantiated class or a mock of your encoder class, or, retrieve TestFixtures class from the client's container. I'm not entirely sure but try $fixture = $this->client->getContainer()->get('App\DataFixtures\TestFixtures');