symfony - 夹具的依赖注入(inject)

标签 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 来将服务传递给 fixture:

services:
_defaults:
    public: true

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

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

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

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

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

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

提前感谢您就此提供的任何建议...

最佳答案

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

关于symfony - 夹具的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51218794/

相关文章:

composer-php - 如何在不安装/更新Composer的情况下将parameters.yml生成为parameters.yml.dist

php - 多个文件上传不将每个路径保存在数据库中

css - Twitter Bootstrap 3 Glyphicons 错误

php - PHP 有自己的 Web 服务器吗?

交响乐。提交表单后,其 CollectionType 字段的 ArrayCollection 中不包含单个元素

php - Symfony2 - Assetic - css 字体图标

php - KnpSnappyBundle 保存文件到服务器

php - 如何在 Symfony2 中正确启用 twig 的沙箱扩展?

Symfony2 : How to update a bundle whose source files have been modified?

php - Doctrine 可指责的扩展 'on change' 不起作用