0

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

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

现在我想通过模拟 staticABC() 函数来编写用于功能测试的 PHPUnit 案例。任何技术人员对此有想法吗?

4

1 回答 1

1

我不认为有一种模拟函数的方法,但你可以做的是使用某种test double

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);
    }
}
于 2013-05-23T10:36:29.137 回答