gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:05:26 28 4
gpt4 key购买 nike

我正在使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com