【问题标题】:phpunit static called method in methodphpunit static 在方法中调用方法
【发布时间】:2017-03-17 09:47:35
【问题描述】:

我有这个方法:

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

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

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

【问题讨论】:

  • 你不能模拟静态方法。
  • 那么我可以测试这个方法吗?
  • 如果你真的想测试它,你可以拦截对静态方法的调用。所以有一个调用静态方法本身的代理类,你可以模拟代理类$this->callProxy($something) 可以模拟,而callProxy($something) 方法可以简单地用$something 调用静态方法
  • 可以使用支持Mock static methodPhake测试库
  • 理想情况下,您应该重构此方法,而不是从中调用全局函数。我会像这样重新定义它:public function getLocale($page) 然后你可以从测试类传递一个模拟页面对象给它。

标签: php unit-testing testing phpunit processwire


【解决方案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。

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2015-01-16
    • 2022-08-22
    • 2020-02-17
    相关资源
    最近更新 更多