PHPUnit模拟父方法

时间:2013-02-12 06:52:02

标签: php unit-testing mocking phpunit

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

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';
    }
}

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

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

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

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

2 个答案:

答案 0 :(得分: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'));

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

$this->assertEquals($expectedParam, $sut->getParam('someParam'));

答案 1 :(得分:4)

我和我的朋友们就像嘲弄图书馆一样。 ouzo-goddies#mocking

$mock = Mock::create('\Appropriate\Namespace\Uri');
Mock::when($mock)->getPath()->thenReturn(result);
相关问题