How do I test a command-line program with PHPUnit?(如何使用 PHPUnit 测试命令行程序?)
问题描述
如何使用 PHPUnit 测试命令行程序?我看到很多关于从命令行使用 PHPUnit 的帮助,但没有看到关于使用 PHPUnit 测试命令行程序本身的帮助.
How do I test a command-line program with PHPUnit? I see plenty of help for using PHPUnit from the command line, but none for testing a command-line program itself with PHPUnit.
这是因为我在 PHP 和 Joomla 中编写命令行程序,但没有看到测试其输出的方法,尤其是在发生错误时(因为您无法使用 PHPUnit 的 expectOutputString()).
This comes up because I am writing command-line programs in PHP and Joomla, but don't see a way to test their output, especially when errors occur (because you cannot test error output using PHPUnit's expectOutputString()).
(请注意,我的大部分代码已经在 PHPUnit 测试的类中——我正在寻找一种方法来测试命令行(包装器)程序的逻辑.)
推荐答案
一种方法是使用反引号运算符 (`) 捕获程序的输出,然后检查该输出.这在 Unix/Linux 风格的操作系统下运行良好,因为您还可以捕获错误输出,如 STDERR.(在windows下比较痛苦,但是可以做到(尤其是使用Cygwin).)
One way is to use the backtick operator (`) to capture the output of the program, then examine that output. This works well under Unix/Linux-style OSes, as you can also capture error outputs like STDERR. (It is more painful under Windows, but can be done (especially using Cygwin).)
例如:
public function testHelp()
{
$output = `./add-event --help 2>&1`;
$this->assertRegExp( '/^usage:/m', $output, 'no help message?' );
$this->assertRegExp( '/where:/m', $output, 'no help message?' );
$this->assertNotRegExp( '/where event types are:/m', $output, 'no help message?' );
}
您可以看到 STDOUT 和 STDERR 都被捕获到 $output,然后使用正则表达式断言来测试输出是否类似于正确的输出.
You can see that both STDOUT and STDERR were captured to $output, then regex assertions were used to test whether the output resembled the correct output.
这篇关于如何使用 PHPUnit 测试命令行程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 PHPUnit 测试命令行程序?


- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Laravel 仓库 2022-01-01