如何在phpunit测试中正确启动php cli脚本?

时间:2013-09-03 03:10:52

标签: php phpunit command-line-interface

我需要测试一些使用stdout,stderr并返回错误代码的php cli脚本。

  • exec似乎没有返回stderr。
  • system不返回stdout(仅限最后一行),stderr。

1 个答案:

答案 0 :(得分:1)

可以使用proc_open。

文件:script.php     

echo 'Standart output'; //stdout

error_log('Error output'); //stderr

exit(1); //return

文件:test.php

<?php

$descriptorspec = array(
    1 => array("pipe", "w"), // stdout is a pipe that the child will write to
    2 => array("pipe", "w") // stderr is a pipe that the child will write to
);

$process = proc_open('php script.php', $descriptorspec, $pipes);
if (is_resource($process))
    {
    echo 'stdout: ' . stream_get_contents($pipes[1]) . PHP_EOL;
    fclose($pipes[1]);

    echo 'stderr: ' . stream_get_contents($pipes[2]) . PHP_EOL;
    fclose($pipes[2]);

    $return_value = proc_close($process);
    echo 'return: ' . $return_value . PHP_EOL;
    }