在PhpUnit上下文

时间:2018-06-04 09:30:31

标签: symfony dependency-injection doctrine phpunit fixtures

我正在使用Symfony 4和PhpUnit,我尝试在Doctrine Fixtures和PhpUnit上下文中注入服务

这是我的fixture的类,你可以看到我在构造函数中注入UserPasswordEncoderInterface

<?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 UserFixtures
 * @package App\DataFixtures
 */
class UserFixtures extends Fixture
{
    /**
     * @var UserPasswordEncoderInterface
     */
    private $encoder;

    /**
     * UserFixtures constructor.
     * @param UserPasswordEncoderInterface $encoder
     */
    public function __construct(UserPasswordEncoderInterface $encoder)
    {
        $this->encoder = $encoder;
    }

    /**
     * @param ObjectManager $manager
     * @throws \Exception
     */
    public function load(ObjectManager $manager)
    {
        $user = new User();
        $user->setFirstname('firstname1');
        $user->setLastname('lastname1');
        $user->setBalance(100);
        $user->setLastUpdateAt(new \DateTime());
        $user->setPlainPassword('test');
        $user->setOptin(true);
        $user->setEnabled(true);
        $user->setEmail('user1@test.fr');
        $user->setPseudo('test');
        $user->setGender(User::GENDER_MALE);
        $user->setBirthdate((new \DateTime())->modify('-20 year'));

        $password = $this->encoder->encodePassword($user, 'test');
        $user->setPassword($password);

        $manager->persist($user);
        $manager->flush();
    }
}

当我这样做时:

bin/console doctrine:fixtures:load 

它完美地工作,并且数据夹具在数据库中正确加载。 我也使用这个灯具进行我的PhpUnit功能测试。所以我在我的测试中加载我的灯具:

$client = static::createClient();
$client->getContainer()->get('doctrine.orm.entity_manager');
$loader = new Loader();
$loader->loadFromDirectory('src/DataFixtures');
$purger = new ORMPurger();
$executor = new ORMExecutor($em, $purger);
$executor->execute($loader->getFixtures(), true);

但PhUnit在这种情况下不理解注射,我有这个错误:

Too few arguments to function App\DataFixtures\UserFixtures::__construct(), 0 passed in /home/psylo/Projects/api-pmu/vendor/doctrine/data-fixtures/lib/Doctrine/Common/DataFixtures/Loader.php on line 193 and exactly 1 expected in /home/psylo/Projects/api-pmu/src/DataFixtures/UserFixtures.php:25

那么如何在phpunit测试中指定注入Doctrine fixtures加载? 还有另一种解决方案吗?

提前帮助你。

1 个答案:

答案 0 :(得分:0)

您可以像这样创建一个bash文件(我通常称之为runtests.sh):

#!/bin/bash

bin/console doctrine:fixtures:load 
./vendor/bin/phpunit 

从CLI启动后:

./runtests.sh

P.S。我不确切地知道如何以这种方式对您的应用程序进行测试:./vendor/bin/phpunit