夹具依赖注入

时间:2018-07-06 23:40:49

标签: symfony

我正在使用Symfony 4构建Web应用程序。我正在尝试从功能测试中加载灯具。我创建了一个夹具类:

<?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('user@gamil.com');
    $user->setIsActive(true);
    $user->setEmail('user@gmail.com');
    $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;
}

}

我已经配置了services_test.yaml以将服务传递给灯具:

services:
_defaults:
    public: true

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

但是,当我尝试运行测试时,出现以下错误:

ArgumentCountError:函数App \ DataFixtures \ TestFixtures :: __ construct()的参数太少,/ Development / app / src / Test / ApiTestCase.php在第38行传递了0个参数,而恰好是1个

这是我测试用例中的函数:

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

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

在此先感谢您提供任何建议...

1 个答案:

答案 0 :(得分:2)

您正在实例化一个类: $fixture = new TestFixtures();,而您需要它作为服务。 您需要这样做$fixture = new TestFixtures(encoder); 其中encoder是实例化类或编码器类的模拟,或者从客户端容器中检索TestFixtures类。我不太确定,请尝试 $fixture = $this->client->getContainer()->get('App\DataFixtures\TestFixtures');