使用 phpunit 测试命令 symfony

ryl*_*ryl 15 php phpunit symfony symfony-3.2

我使用 symfony3.2 创建一些基本命令来定期生成一些新闻通讯,当我想使用 phpunit 5.5.4 测试我的 symfony 命令时,我正在处理一些问题。它从一开始就失败了:

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

        $output->writeln("<info>Script start</info>");
        //...
        $output->writeln("<info>done</info>");
     }
Run Code Online (Sandbox Code Playgroud)

通过这个单元测试:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我一步一步地遵循这个步骤,但就我而言,我得到:

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
Run Code Online (Sandbox Code Playgroud)

似乎 commandTester 没有在 MyCommand 的执行方法中放入正确的参数。我想知道这是否不是 CommandTesterClass 问题。

这就是为什么我在这里与大家分享并共同寻找解决方案。

先感谢您

小智 9

方法“getDisplay()”返回一个字符串,正如您可以从 Api 文档中看到的那样: http: //api.symfony.com/3.0/Symfony/Component/Console/Tester/CommandTester.html并且您将该字符串分配给您的$输出变量。我认为你需要的是“getOutput()”