9951 explained code solutions for 126 technologies


phpunitHow to mock a private method in PHPUnit?


Mocking private methods in PHPUnit is possible using the getMockBuilder method.

$mock = $this->getMockBuilder(MyClass::class)
    ->setMethods(['myPrivateMethod'])
    ->getMock();

$mock->expects($this->once())
    ->method('myPrivateMethod')
    ->willReturn('mocked result');

The above code will create a mock object of MyClass and override the myPrivateMethod method with a mocked result.

  • getMockBuilder: creates a mock object of the specified class
  • setMethods: overrides the specified methods with mocked results
  • expects: specifies the expectation of the mocked method
  • method: specifies the method to be mocked
  • willReturn: specifies the return value of the mocked method

Helpful links

Edit this code on GitHub