php - 如何从 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
解决方案
尝试在 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);
}
推荐阅读
- python - 从 Excel 工作表写入表格
- selenium - TestNg 中的静态和非静态
- c++ - 拼接图像无法检测到共同特征点
- reporting - 工作日添加 SSRS
- javascript - 向下滚动鼠标光标时如何固定顶部标题
- javascript - react/js函数调用
- android - 二进制 XML 文件第 28 行:二进制 XML 文件第 28 行:膨胀类时出错
- node.js - redis/memcached 缓存与 Etag 缓存有何不同?
- kubernetes - 如何创建将基于架构部署的 k8s 部署文件
- java - 如何在 InfluxDB 中创建一个带有 2 个小数的浮点字段