在PHP中有一种测试CLI交互的方法


In PHP is there a way to test CLI interaactions?

标题中的问题。我遇到问题的测试方法示例是:https://github.com/rzajac/phptools/blob/master/src/Cli/Interaction.php#L36

如果使用了名称空间,则可以模拟fgets()。

namespace My'Namespace;
class SomeClass
{
    public static function getPassword($prompt = '')
    {
        echo $prompt;
        'system('stty -echo');
        // Notice how the global function "fgets()" is called without the leading backslash 
        // (relative instead of absolute call in a namespaced environment). 
        // This will let us later mock the call
        $pass = fgets(STDIN);
        'system('stty echo');
        return $pass;
    }
}

测试文件:

namespace My'Namespace {
    // And this here, does the trick: it will override the fgets()
    // function in your code *just for the namespace* where you are defining it.
    function fgets($Handle) {
        return 'Pa$$Word';      // Password Text for testing
    }
include_once './SomeClass.php';
class Test_SomeClass extends 'PHPUnit_Framework_TestCase
{
    /**
     * This will test the success case.
     * @test
     */
    public function testPass()
    {
        $dummy = new 'My'Namespace'SomeClass;
        $this->assertEqual('Pa$$Word', $dummy->getPassword());
    }
}

这篇文章还讨论了一个处理异常的套接字示例。

相关文章: