Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: How to mock private methods? [duplicate]

I have a class like this:

class A {

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

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

}

To invoke testing() 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 want testing only the code in testing() method. I want to point out what I want privateMethod() to return result without actually method to be called.

like image 742
micobg Avatar asked Feb 06 '26 01:02

micobg


1 Answers

If you can change private to protected, you would be able to use partial mocks for this.

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

This will replace the implementation only on the methods in the setMethods array, and all other methods will execute the original code. This however do not work for private methods, as the mock objects extends the original one; but it can not override the private.

like image 163
Maxim Krizhanovsky Avatar answered Feb 07 '26 15:02

Maxim Krizhanovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!