5

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

6

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.

2
  • 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
    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
    Jun 27, 2020 at 10:04

Your Answer

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

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