9951 explained code solutions for 126 technologies

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');

echo MyClass::myStaticMethod();

Output example


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 class
  • expects: specifies the expectation of the mock object
  • method: specifies the method to be overridden
  • will: specifies the return value of the overridden method

Helpful links

Edit this code on GitHub