我使用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>");
}
使用此单元测试:
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);
}
}
我按照这个步骤逐步操作,但在我的情况下出现了:
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
看起来像是commandTester在执行MyCommand时没有正确的参数。我在想这是否是CommandTester类的问题。
这就是为什么我在这里分享,并希望一起找到解决方案。
提前感谢你。