如何使用 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.
相关文章