Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit mock throws incompatible declaration error

I'm using PHPUnit 3.6.10 (unfortunately I can't upgrade to newer version at the moment). While dealing with mocking of some legacy code, I got a weird error. Tried google, only results related to static methods came up, which is not my case.

Having this class:

class ServicesMapper extends DbMapper
{
    //... (some methods)

    public function saveTravel(ServiceTravel $oTravel) {
        $this->getAdapter()->insert('services_travels', $oTravel->getToArray());
    }

    //... (some methods)
}

I try to mock it:

(inside unit test class)

/**
 * @return ServicesMapper
 */
private function getServicesMapperStub()
{
    $stub = $this->getMock('ServicesMapper');

    $stub->expects($this->any())
            ->method('searchBy')
            ->will($this->returnValue(array()));

    return $stub;
}

Now, while running this fake test (I know this test does nothing, this is just to show issue):

   /**
    * @test
    */
    public function fakeMockTest(){
        $serviceMapper = $this->getServicesMapperStub();
        $this->assertTrue(true);
    }

I get this error:

Declaration of Mock_ServicesMapper_60b00178::saveTravel() 
should be compatible with ServicesMapper::saveTravel(ServiceTravel $oTravel)

I use this style of mocking in a lot of places, it works well except for this particular case. What's wrong with my code?

BTW: I also tried to solve this issue by mocking saveTravel method, with no luck.

like image 699
ex3v Avatar asked Dec 05 '14 14:12

ex3v


1 Answers

Your code looks correct, and might work with simple stubs, not mocks (basically, a stub with expectations).

For mocks you need to do:

$mock = $this->getMockBuilder('ServicesMapper')
             ->setMethods(array ('searchBy'))
             ->getMock();

All the methods you want to set expectations for should be declared on setMethods().

like image 189
Edson Medina Avatar answered Sep 19 '22 03:09

Edson Medina