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 skip a PHPUnit test?
- How to show warnings in PHPUnit?
- How to stop PHPUnit on failure?
- How to mock a query builder with PHPUnit?
- How to install PHPUnit with a PHAR file?
- How to run tests in parallel with PHPUnit?
- How to order tests with PHPUnit?
- How to ignore a test in PHPUnit?
- How to run PHPUnit in a Docker container?
- How to configure PHPUnit?
See more codes...