M
M
memba2016-03-01 13:57:50
PHP
memba, 2016-03-01 13:57:50

How to properly test a CLI application in PHP using PHPUnit?

Hey!
I have a simple PHP command line application. What is the best way to test it with PHPunit?
The first thing that came to mind:

class HelloTest extends \PHPUnit_Framework_TestCase
{
    public function testHello()
    {
        $expect = "<<HelloWorld>>";
        $result = shell_exec("php command HelloWorld");
        $result = trim($result);
        $this->assertEquals($result, $expect);
    }
}

It simply passes the string HelloWorld to the application, and it is returned enclosed in angle brackets.
Is it correct to use shell_exec or does PHPUnit have some built-in capabilities?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Voronkov, 2016-03-02
@DmitryVoronkov

Why would you want to emit a console?
Unit testing, as far as I remember, is unit testing.
Check like this:

class HelloTest extends \PHPUnit_Framework_TestCase
{
    public function testHello()
    {
        $expect = "HelloWorld";
        $command = new Command();
        $result = $command->helloWorld();
        $this->assertEquals($result, $expect);
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question