phpunit-testingsymfony-3.4symfony-console

How set console argument in symfony 3 console command testing


I am unable to set Argument while creating Unit test case in Symfony 3.4 console command application

My Console command

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

My Console code

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!');
    }
}

I tried the following test code

$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);

When I run unit test it showing the following error message

There was 1 error:

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

Solution

  • I think you should put your input in the command tester and not in the command finder, in this case you are trying to create another parameter for that command, and that's why it's telling you that it is existing already. try this

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