5

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

1
  • You could group your command line script logic into functions/classes, and then test those functions and classes Commented Jul 17, 2013 at 13:14

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Test the same way you would a web page, simply write the tests and execute them against your code. This is assuming that you are testing the objects of your program, and not the return of the code from a command line program.

Your code contains classes that execute and manipulate data. just without a web page being generated. Simply write the same tests for the classes, data manipulations, etc... as you are running the tests against the pieces of the code, not the complete executable.

I have a class that parses command line options for instance, and allows code to iterate over the values. I wrote tests to pass the command line to the object (without reading the actual args, argv) and then can test that it returns correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.