首页 > 解决方案 > 如何从 symfony 3.4 中的测试类传递 ContainerInterface

问题描述

我正在 Symfony 单元测试中测试命令行应用程序,在我的命令类中我通过构造函数使用容器接口。

当我使用单元测试对其进行测试时,它返回以下错误 Too few arguments to function AppBundle\Command\DocumentCommand::__construct(), 0 passed

我的命令类

use Symfony\Component\DependencyInjection\ContainerInterface as Container;

class DocumentCommand extends Command
{
    private $container;
    // the name of the command (the part after "bin/console")
    protected static $defaultName = 'identification-requests:process';

    public function __construct(Container $container, bool $requirePassword = false)
    {
        $this->container = $container;
        $this->base_path = $this->container->get('kernel')->getRootDir();

        $this->requirePassword = $requirePassword;

        parent::__construct();
    }

测试班

use Symfony\Component\DependencyInjection\ContainerInterface;

class DocumentCommandTest extends KernelTestCase
{
    /** @var  Application $application */
    protected static $application;

    /** @var  Client $client */
    protected $client;

    /** @var  ContainerInterface $container */
    protected $container;

    /**
     * Test Execute
     *
     */
    public function testExecute()
    {
        $kernel = static::createKernel();
        $kernel->boot();

        $application = new Application($kernel);
        $application->add(new DocumentCommand());

        $command = $application->find('identification-requests:process');
        $commandTester = new CommandTester($command);
        $commandTester->execute(array(
            'command' => $command->getName(),
            'file' => 'input.csv'
        ));

        $output = $commandTester->getOutput();
        $this->assertContains('valid',$output);
    }
}

我试图从测试类传递容器接口但没有用。以下是错误信息

1) Tests\AppBundle\Command\DocumentCommandTest::testExecute
ArgumentCountError: Too few arguments to function AppBundle\Command\DocumentCommand::__construct(), 0 passed in \tests\AppBundle\Command\DocumentCommandTest.php on line 34 and at least 1 expected

标签: phpunit-testingphpunitconsole-applicationsymfony-3.4

解决方案


尝试在 testExecute 中传递容器:

$application->add(new DocumentCommand($kernel->getContainer()));

public function testExecute()
{
    $kernel = static::createKernel();
    $kernel->boot();

    $application = new Application($kernel);
    $application->add(new DocumentCommand($kernel->getContainer()));

    $command = $application->find('identification-requests:process');
    $commandTester = new CommandTester($command);
    $commandTester->execute(array(
        'command' => $command->getName(),
        'file' => 'input.csv'
    ));

    $output = $commandTester->getOutput();
    $this->assertContains('valid',$output);
}

推荐阅读