模拟一个单独类的函数


Mocking the function of a separate class

我有一个函数测试,它返回属于单独类的静态函数staticABC的响应

function test()
{
   return testA::staticABC();
}

现在我想通过模拟staticABC()函数来编写PHPUnit用例进行功能测试。有技术人员知道这个吗?

我不认为有一种模拟函数的方法,但你可以做的是使用某种测试双精度:

class SUT{
    $staticCreator = array('testA::staticABC'); //Initialized to a default 
             //for production, would be better if injected somehow before using
    function setStaticCreator($staticCreator){
        $this->staticCreator=$staticCreator;
    }
    function test(){
        return call_user_func($this->staticCreator);
    }
}

,然后这样运行测试:

class Test extends ...{
    function mockStaticABC(){
        return "mock_string";
    }
    test_testfunction(){
        $sut = new SUT();
        $staticCreator = array($this,'mockStaticABC');
        $sut->setStaticCreator($staticCreator);
        $mock_return = $sut->test();
        $this->assertEquals("mock_string",$mock_return);
    }
}