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 测试命令行程序?
 
				
         
 
            
        基础教程推荐
- 将变量从树枝传递给 js 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php中的PDF导出 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- php中的foreach复选框POST 2021-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
				 
				 
				 
				