Php单元测试,受保护的方法与模拟


Php unit testing, protected method with mocking

我是TDD的新手。我被困在一些单元测试中...请看一下我的代码...提前感谢...

class Parser{
    protected function _checkCurlExistence()
    {
        // Unable to to mock function_exists, thats why fallback with this method
        return function_exists('curl_version');
    }

    public function checkCurlExtension()
    {
        // I want to test 2 situations from this method...
        // 1. if curl extension exists
        // 2. or when curl extension does not exists...throw error
        if($this->_checkCurlExistence() === false){
            try{
                throw new CurlException(); //Some curl error handler exception class
            }catch(CurlException $error){
                exit($error->getCurlExtensionError());
            }
        }
        return true;
    }
}

想要测试:

class ParserTest{
    /**
    * @expectedException CurlException
    */
    public function testCheckCurlExtensionDoesNotExists()
    {
        //Some testing code with mocking...
    }
    public function testCheckCurlExtensionExists()
    {
       //Some testing code with mocking..and assertion 
    }
}

我的问题/要求:

你能填写这些测试吗?我永远被困在这个上面...并且无法继续我的TDD之旅。

一些步骤(您可以跳过这些行(:

我已经尽力自己解决这个问题,但无法做到这一点。一些步骤是..

我尝试了phpunit的原生嘲弄padraic/mockery(git(,codeception/aspect-mock(git(来模拟_checkCurlExist((方法,用于两种情况...我不确定我是否做对了...这就是为什么,不发布这些代码...

我尝试了反射 API,类扩展通过魔术方法 __call((...动态地将受保护的方法转换为公共方法以帮助模拟...

我也做了很多谷歌搜索。了解最佳实践是仅测试公共方法。但是我的公共方法依赖于受保护的方法...那么我该如何测试呢???

找到了一种通过以下方式模拟 php 内置函数的方法PHPUnit 函数模拟器扩展

所以我现在可以轻松测试这两个场景。

namespace 'myNameSpace';
class Parser{
    public function checkCurlExtension()
    {
        // I want to test 2 situations from this method...
        // 1. if curl extension exists
        // 2. or when curl extension does not exists...throw error
        if(function_exists('curl_version') === false){
            throw new CurlException(); //Some curl error handler exception class
        }
        return true;
    }

}
class ParserTest{
    private $parser;
    /**
    * @expectedException CurlException
    */
    public function testCheckCurlExtensionDoesNotExists()
    {
        $funcMocker = 'PHPUnit_Extension_FunctionMocker::start($this, 'myNameSpace')
        ->mockFunction('function_exists')
        ->getMock();
        $funcMocker->expects($this->any())
        ->method('function_exists')            
        ->will($this->returnValue(false));
        $this->parser->checkCurlExtension(); 
    }
    public function testCheckCurlExtensionExists()
    {
       //we can do same here...please remember DRY...
    }
}