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.

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

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏