2

I have this method:

public function getLocale()
    {
        $languageId = $this->_user->language->id;
        $page = Wire::getModule('myModule')->getPage($languageId);
        $locale = $page->locale;

        if (!!$locale) {
            return $locale;
        }

        // fallback to browser's locale
        $browserLocale = new SBD_Language();
        $locale = $browserLocale->getLanguageLocale('_');

        return $locale;
    }

Now I want to write a test for it, but I get this error: Trying to get property of non-object which is caused by Wire::getModule('myModule').

So I'd like to override the Wire::getModule response with phpunit. I just don't know how to do that.

So far I have created a mock over the class in which the method getLocale is placed and that is all working fine but how would I tell that mock class that it should actually call a mock of the Wire class?

8
  • You can't mock static methods. Commented Mar 17, 2017 at 9:49
  • So can I test this method than? Commented Mar 17, 2017 at 9:51
  • You could intercept the call to the static method if you really wish to test it.. So have a proxy class that calls the static method itself, you can mock that proxy class $this->callProxy($something) can be mocked, and the callProxy($something) method could simply call the static method with $something Commented Mar 17, 2017 at 9:53
  • You can use Phake test library that support Mock static method Commented Mar 17, 2017 at 9:54
  • 2
    Ideally you should refactor this method and not call global functions from it. I would redefine it like this: public function getLocale($page) then you can pass a mock page object to it from the test class. Commented Mar 17, 2017 at 10:17

1 Answer 1

1

You can kind of mock static methods by proxying the call to the static method, as such

class StaticClass
{
    static function myStaticFunction($param)
    {
        // do something with $param...
    }
}

class ProxyClass
{
    static function myStaticFunction($param)
    {
        StaticClass::myStaticFunction($param);
    }
}

class Caller
{
    // StaticClass::myStaticFunction($param);
    (new ProxyClass())->myStaticFunction($param); 
    // the above would need injecting to mock correctly
}

class Test
{
    $this->mockStaticClass = \Phake::mock(ProxyClass::class);
    \Phake::verify($this->mockStaticClass)->myStaticMethod($param);
}

That example is with Phake, but it should work with PHPUnit the same way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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