PHPUnit模拟父方法

Pio*_*ski 6 php phpunit unit-testing mocking

我有模拟父方法的问题,这是一个例子:

class PathProvider
{
    public function getPath()
    {
        return isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
    }
}


class Uri extends PathProvider
{
    public function getParam($param)
    {
        $path = $this->getPath();

        if ($path == $param)
            return 'OK';
        else
            return 'Bad';
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想要模拟方法getPath(),并调用方法getParam()来获取模拟值.

$mock = $this->getMock('PathProvider');

$mock->expects($this->any())
->method('getPath')
->will($this->returnValue('/panel2.0/user/index/id/5'));
Run Code Online (Sandbox Code Playgroud)

我写这部分,但我不知道如何将这个模拟值传递给测试方法.

Cyp*_*ian 5

你只需要模拟Uri课程.你可以只模拟一个方法(getPath),就像那样:

$sut = $this->getMock('Appropriate\Namespace\Uri', array('getPath'));

$sut->expects($this->any())
    ->method('getPath')
    ->will($this->returnValue('/panel2.0/user/index/id/5'));
Run Code Online (Sandbox Code Playgroud)

然后你可以像往常一样测试你的对象:

$this->assertEquals($expectedParam, $sut->getParam('someParam'));
Run Code Online (Sandbox Code Playgroud)