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 mock a method with different arguments in PHPUnit?
- How to generate a JUnit report in PHPUnit?
- How to show warnings in PHPUnit?
- How to skip a PHPUnit test?
- How to run PHPUnit in quiet mode?
- How to run tests in parallel with PHPUnit?
- How to mock an interface in PHPUnit?
- How to log with PHPUnit?
- How to use JSON in PHPUnit?
See more codes...