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 show warnings in PHPUnit?
- How to skip a PHPUnit test?
- How to run tests in parallel with PHPUnit?
- How to stop PHPUnit on failure?
- What are PHPUnit required extensions
- How to mock a query builder with PHPUnit?
- How to run all PHPUnit tests?
- How to install PHPUnit with a PHAR file?
- How to use named arguments in PHPUnit?
- How to mock with PHPUnit?
See more codes...