【问题标题】:Validate Command Monolog Output in Symfony 4 Unit Test在 Symfony 4 单元测试中验证命令独白输出
【发布时间】:2019-04-25 09:28:50
【问题描述】:
【问题讨论】:
标签:
php
unit-testing
command
symfony4
monolog
【解决方案1】:
我已经通过在 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');
}
}
任何人对如何验证输出有任何其他建议吗?