方法中的phpunit静态调用方法 [英] phpunit static called method in method

查看:75
本文介绍了方法中的phpunit静态调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法:

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')引起的.

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

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

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

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

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?

推荐答案

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

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

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

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

这篇关于方法中的phpunit静态调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆