douluo5937 2015-11-05 11:08
浏览 67
已采纳

在PHP中有没有办法测试CLI交互?

The question like in the title. The example method I have problems testing is: https://github.com/rzajac/phptools/blob/master/src/Cli/Interaction.php#L36

  • 写回答

1条回答 默认 最新

  • doutangxi2144 2015-11-05 17:59
    关注

    You can mock the fgets() if you have namespaces in use.

    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;
        }
    }
    

    The Test file:

    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());
        }
    }
    

    This Post discusses a socket example as well that handles exceptions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan