phpunitHow to mock a static method with PHPUnit?
Mocking static methods with PHPUnit is possible using the getMockForAbstractClass
method.
class MyClass
{
public static function myStaticMethod()
{
return 'foo';
}
}
$mock = $this->getMockForAbstractClass('MyClass');
$mock->expects($this->any())
->method('myStaticMethod')
->will($this->returnValue('bar'));
echo MyClass::myStaticMethod();
Output example
bar
The code above creates a mock object of the MyClass
class and overrides the myStaticMethod
method to return bar
instead of foo
.
Code explanation
getMockForAbstractClass
: creates a mock object of the specified classexpects
: specifies the expectation of the mock objectmethod
: specifies the method to be overriddenwill
: specifies the return value of the overridden method
Helpful links
More of Phpunit
- How to stop PHPUnit on failure?
- How to skip a PHPUnit test?
- How to show warnings in PHPUnit?
- What are PHPUnit required extensions
- How to mock a query builder with PHPUnit?
- How to install PHPUnit from Packagist?
- How to use JSON in PHPUnit?
- How to run all PHPUnit tests?
- How to test private methods in PHPUnit?
- How to use the PHPUnit Framework TestCase?
See more codes...