2

我有这个方法:

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;
    }

现在我想为它写一个测试,但我得到这个错误: Trying to get property of non-object这是由Wire::getModule('myModule').

所以我想Wire::getModule用phpunit覆盖响应。我只是不知道该怎么做。

到目前为止,我已经在getLocale放置该方法的类上创建了一个模拟,并且一切正常,但是我将如何告诉该模拟类它实际上应该调用Wire该类的模拟呢?

4

1 回答 1

1

您可以通过代理对静态方法的调用来模拟静态方法,例如

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

该示例使用 Phake,但它应该以相同的方式与 PHPUnit 一起使用。

于 2017-03-17T10:11:10.640 回答