I have a custom service defined by my module and in one of its methods I call a static method from a class defined by a module mine depends on. Since this method is static I do not need to instantiate an object but this also means I cannot inject the dependency. Soooo... How do I mock the static call?

Here is some psuedo code to illustrate:

use some/other/class/called/FOO


function myMethod() {
  // Do some things...
  $some_var = FOO::staticMethodToGetValue();
  // Do more things...
  return "something";    

1 Answer 1


You can't mock static calls directly.

A relatively easy way to fix this is what core uses in quite some places to mock functions that haven't been converted to objects/services yet. You create a method in your own class that does nothing but call the static method.

Then for your test, you can either mock your own object and only mock that method or create a test subclass that overrides that method and return something else.

  • I was afraid that this was going to be the answer. In my actual case Ill have to create 4 otherwise useless little methods and that makes me sad. Thanks though!
    – bleen
    Commented Jul 30, 2016 at 17:01
  • Just for reference, this documentation page on drupal.org demonstrates a similar case: drupal.org/docs/testing/phpunit-in-drupal/…
    – Juhog
    Commented Jun 27, 2020 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.