0

在 Symfony 3.4 控制台命令应用程序中创建单元测试用例时,我无法设置参数

我的控制台命令

php bin\console identification-requests:process input.csv

我的控制台代码

protected function execute(InputInterface $input, OutputInterface $output)
{
    // Retrieve the argument value using getArgument()
    $csv_name = $input->getArgument('file');

    // Check file name
    if ($csv_name == 'input.csv') {
        // Get input file from filesystem
        $csvData = array_map('str_getcsv', file($this->base_path.$csv_name));
        $formatData = Helpers::formatInputData($csvData);

        // Start session
        $session = new Session();
        $session->start();

        foreach ($csvData as $key => $data) {
            if (!empty($data[0])) {
                $validation = Validator::getInformationData($data, $formatData[$data[1]]);
                if (!empty($validation)) {
                    $output->writeln($validation);
                } else {
                    $output->writeln('valid');
                }
            }
        }
    } else {
        $output->writeln('Invalid file!');
    }
}

我尝试了以下测试代码

$kernel = static::createKernel();
$kernel->boot();

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

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

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

当我运行单元测试时,它显示以下错误消息

There was 1 error:

1) Tests\AppBundle\Command\DocumentCommandTest::testExecute
Symfony\Component\Console\Exception\LogicException: An argument with name "file" already exists.
4

1 回答 1

2

我认为您应该将输入放在命令测试器中而不是命令查找器中,在这种情况下,您正在尝试为该命令创建另一个参数,这就是为什么它告诉您它已经存在。尝试这个

$command = $application->find('identification-requests:process');
$commandTester = new CommandTester($command);
$commandTester->execute(array(
    'command' => $command->getName(),
    'file' => 'input.csv'
));
于 2019-08-26T20:10:42.830 回答