test command symfony with phpunit
Asked Answered
R

1

15

I create some basic command with symfony3.2 to generate some newsletter periodically I'm dealing with some issue when i want to test my symfony command with phpunit 5.5.4. It fail from the beginning:

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     */
    protected function execute(InputInterface $input, OutputInterface $output){

        $output->writeln("<info>Script start</info>");
        //...
        $output->writeln("<info>done</info>");
     }

with this unit test:

use MyBundle\Command\MyCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;

class MyCommandTest extends KernelTestCase
{

    public function testExecute(){

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

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

        $command = $application->find('generate:newsletter');
        $commandTester = new CommandTester($command);
        $commandTester->execute(array(
            'command' => $command->getName()
        ));

        $output = $commandTester->getDisplay();
        $this->assertContains('done',$output);
    }
}

I follow this step by step but in my case i get :

Error: Call to a member function writeln() on string

MyBundle/Command/MyCommand.php:197
vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:262
vendor/symfony/symfony/src/Symfony/Component/Console/Tester/CommandTester.php:84
MyBundle/Command/MyCommandTest.php:34

It seems like commandTester don't put correct parameter in execute method from MyCommand. I'm wondering if it's not CommandTesterClass issue.

That's why i'm here, to share with you that and find some solution together.

Thank you in advance

Rambling answered 8/11, 2017 at 15:15 Comment(1)
Ok, i found the probleme. In MyCommand class, i use two variable with same name. One for get template and another from OutputInterface. After i get template i call writeln to display "done" but from wrong class. After renaming my variables, it's done. Sorry for the troubleRambling
D
9

Method 'getDisplay()' returns a string as you can see from the Api doc: http://api.symfony.com/3.0/Symfony/Component/Console/Tester/CommandTester.html and you're assigning that string to your $output variable. I think what you need is 'getOutput()'

Devotee answered 8/11, 2017 at 15:21 Comment(3)
Thank you for your fast reply. I tried with getOuput method and it's same issue. I don't think it's MyCommandTest problemRambling
Hmm does your command work when running from console? Can you provide 198 and 197 lines from MyCommand.php?Devotee
Yes that's it. I override some commandtester variable i used. that's why i get this error. thank you for your help and sorry for troubleRambling

© 2022 - 2024 — McMap. All rights reserved.