php - 在 Symfony 4 单元测试中验证命令独白输出
问题描述
在https://symfony.com/doc/current/console.html#testing-commands 用户可以看到如何使用单元测试来测试命令。
问题是在此过程之后,无法测试通过 Monolog 生成的控制台输出。
$output = $commandTester->getDisplay();
# Returns ''
因此,$output 上的所有断言都是错误的。
有人知道如何在 Symfony 4 的 Symfony 命令中对 Monolog 输出进行单元测试吗?
解决方案
我已经通过在 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');
}
}
有人对如何验证输出有任何其他建议吗?
推荐阅读
- reactjs - 使用最新版本 0.29.3 对字符串类型进行 Formik 和 yup 验证
- dialogflow-cx - Dialogflow CX 版:如何查看对话
- xml - 从机器人框架的xml文件中的另一个属性值获取属性值
- java - 插入关系表时,房间多对多关系 UNIQUE 约束失败
- sql - 无法在 BigQuery 中选择列
- xquery - 如何在不同元素中的数据的构面内获取单行数据
- python - 如何将项目附加到对象数组?
- c# - 散列密码显示奇怪
- javascript - PHP:如何先使用变量,然后在 PHP 中初始化它(使用 Jquery 或 Ajax)?
- python - AWS Glue 调用 o128.resolveChoice 时出错