Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test command symfony with phpunit

Tags:

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

like image 253
ryl Avatar asked Nov 08 '17 15:11

ryl


1 Answers

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()'

like image 76
avpav Avatar answered Oct 05 '22 13:10

avpav