在Symfony 4单元测试中验证命令Monolog输出

时间:2018-11-22 16:47:10

标签: php unit-testing command symfony4 monolog

https://symfony.com/doc/current/console.html#testing-commands中 用户可以看到如何使用单元测试来测试命令。

问题在于,执行此过程后,将无法测试通过Monolog进行的控制台输出。

$output = $commandTester->getDisplay();
# Returns ''

因此,在$ output上的所有断言都是假的。

有人知道如何在Symfony 4的Symfony命令中对Monolog输出进行单元测试吗?

1 个答案:

答案 0 :(得分:0)

我设法通过在monolog“ config / packages / test / monolog.yaml”中添加TestHandler来测试Monolog输出

monolog:
    handlers:
        test:
            type: test
            level: debug

这是我的TestClass中的代码

class MyClassCommandTest extends KernelTestCase
{
    /**
     * First validation tests all invalid options
     */
    public function testMyCommand()
    {
        $kernel = static::createKernel();
        $application = new Application($kernel);

        $command = $application->find('my:command:name');
        $commandTester = new CommandTester($command);

        $options['command'] = $command->getName();
        $commandTester->execute([
            'option_name' => 'value'
        ], [
            'verbosity' => OutputInterface::VERBOSITY_VERY_VERBOSE
        ]);

        //I injected the logger inside my command and added a function getLogger to access it
        $logger = $command->getLogger();
        $handlers = $logger->getHandlers();

        $logs = null
        foreach ($handlers as $handler) {
            if ($handler instanceof TestHandler) {
                $logs = $handler;
            }
        }

        $this->assertTrue($logs->hasRecordThatContains('ERROR_STRING_1', Logger::ERROR), 'Missing Error');
        $this->assertTrue($logs->hasRecordThatContains('CRITICAL_STRING_1', Logger::CRITICAL), 'Missing Critical Error');
        $this->assertFalse($logs->hasRecordThatContains('SUCCESS_STRING_1', Logger::INFO), 'Has Success Message');
    }
}

有人对如何验证输出有其他建议吗?