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 classsetMethods: overrides the specified methods with mocked resultsexpects: specifies the expectation of the mocked methodmethod: specifies the method to be mockedwillReturn: specifies the return value of the mocked method
Helpful links
More of Phpunit
- How to mock a method with different arguments in PHPUnit?
- How to skip a PHPUnit test?
- How to show warnings in PHPUnit?
- How to mock an interface in PHPUnit?
- How to use filters with PHPUnit?
- How to run PHPUnit in a Docker container?
- How to clear the PHPUnit cache?
- How to stop PHPUnit on failure?
- How to run all PHPUnit tests?
- How to install PHPUnit with Composer?
See more codes...