Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

php - How do I test a command-line program with 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.

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()).

(EDIT: Note that the bulk of my code is already in classes which are tested by PHPUnit -- I'm looking for a way to test the command-line (wrapper) program's logic.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).)

For example:

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?' );
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...