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 run tests in parallel with PHPUnit?
- How to run PHPUnit in quiet mode?
- How to use hooks in PHPUnit?
- How to use the PHPUnit command line interface (CLI)?
- How to mock an interface in PHPUnit?
- PHPUnit usage example
- How to run PHPUnit in a Docker container?
- How to use Faker with PHPUnit?
- How to clear the PHPUnit cache?
See more codes...