如何使用PHPUnit测试命令行程序? [英] How do I test a command-line program with PHPUnit?

查看:337
本文介绍了如何使用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风格的OS上很好用,因为您还可以捕获错误输出(如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测试命令行程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆