Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit mock parent method

I have problem with mocking parent method, this is example:

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

And now i want mock method getPath(), and call method getParam() which recive mocked value.

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

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

I was write this part, but I don't know how I must pass this mocked value to testing method.

like image 809
Piotr Olaszewski Avatar asked Feb 12 '13 06:02

Piotr Olaszewski


Video Answer


2 Answers

You just need mock Uri class. You can mock only one method (getPath), like that:

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

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

And then you can test your object as usual:

$this->assertEquals($expectedParam, $sut->getParam('someParam'));
like image 140
Cyprian Avatar answered Oct 15 '22 07:10

Cyprian


Me and my friends write mockito like mocking library. ouzo-goddies#mocking

$mock = Mock::create('\Appropriate\Namespace\Uri');
Mock::when($mock)->getPath()->thenReturn(result);
like image 21
Piotr Olaszewski Avatar answered Oct 15 '22 08:10

Piotr Olaszewski