PHPUnit: How to mock private methods?

I have a class like this:

class A {

    private function testing($x)
    {
        // do something
        $this->privateMethod();
    }

    private function privateMethod($number) {
        // do something
    }

}

      

To call test () I use this:

$reflection = new \ReflectionClass('A');
$method = $reflection->getMethod('testing');
$method->setAccessible(TRUE);

$object = new A();
$parameters = array();
$result = $method->invokeArgs($object, $parameters);

      

But I don't know how to mock privateMethod (). I only want to test the code in the testing () method. I want to point out that I want privateMethod () to return a result without actually calling the method.

+3


source to share


1 answer


If you can change private to protected, you can use partial layouts for that.

$object = $this->getMockBuilder('A')
    ->setMethods(array('privateMethod'))
    ->getMock();
$object->expects($this->any())
    ->method('privateMethod')
    ->will($this->returnValue($x));

      



This will replace the implementation with only methods on the array setMethods

, and all other methods will execute the original code. However, this does not work for private methods, since mock objects extend the original one; but it cannot override private

.

+5


source







All Articles