Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHPUnit模拟父方法_Php_Unit Testing_Mocking_Phpunit - Fatal编程技术网

PHPUnit模拟父方法

PHPUnit模拟父方法,php,unit-testing,mocking,phpunit,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) { $p

我对模仿父方法有问题,以下是示例:

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';
    }
}
现在我需要mock方法getPath(),并调用方法getParam(),该方法接收mock值

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

$mock->expects($this->any())
->method('getPath')
->will($this->returnValue('/panel2.0/user/index/id/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'));

我和我的朋友们写mockito就像是写mocking library一样


我认为应该重新设计,Uri不是路径提供者,它只需要它的服务。@GordonM完全正确!您应该将PathProvider作为依赖项,并将其注入Uri类中(通过controller或Setter)。当我调用像您这样的方法时,请不要过度使用In-Ritance告诉我收到错误:
调用未定义的方法Mock\u Uri\u b1cf6492::getParam()
可能您忘记了为getMock方法添加适当的命名空间。看看我的应用程序上面的例子(我会编辑答案),我有正确的名称空间,但我总是有上面的错误。我的错误,对不起-一切都好。我设置了错误的引导加载程序来启动测试。
$mock = Mock::create('\Appropriate\Namespace\Uri');
Mock::when($mock)->getPath()->thenReturn(result);