如何模拟其他类使用的全局函数和类 [英] how to mock global functions and classes used by another class

查看:97
本文介绍了如何模拟其他类使用的全局函数和类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个测试,我的方法之一利用了一个全局函数web(),该函数接受一个(字符串)URL,并创建并返回UrlHelper的新实例.这为我的应用程序提供了一些帮助方法的捷径. (是的,DI会更好,但这是在较小的应用程序中...)

I am trying to write a test, and one of my methods makes use of a global function web() which takes a (string) url, and creates and returns new instance of UrlHelper. This gives my app some shortcuts to some helper methods. (Yes DI would be better, but this is in a larvel app...)

我要测试的方法,使用此全局帮助器获取给定url的内容,并将其与另一个字符串进行比较.

The method I'm trying to test, uses this global helper to get the content of the given url and compares it to another string.

使用phpunit,我如何截获对web的调用或创建UrlHelper的调用,以便确保它返回给定的响应?代码看起来像下面的

Using phpunit, how can i intercept the call to web or the creation of UrlHelper so i can ensure it returns a given response? the code looks a bit like the following

function web($url){
 return new \another\namespace\UrlUtility($url);
}

...

namespace some/namespace;

class checker {
   function compare($url, $content){
       $content = web($url)->content();
       ...logic...
       return $status;
   }
}

单元测试正在测试比较的逻辑,所以我想从web调用中获得预期的内容.我希望模拟/存根能够解决问题-但我不确定是否可以使用此全局函数或其他未传入的类?

The unit test is testing the logic of compare, so i want to get expected content from the web call. I was hoping mocks/stubs would do the trick - but I'm not sure if i can hit this global function or another class which isn't passed in?

谢谢

推荐答案

您可以使用Mockery重载该类,然后更改该方法的实现.

You can overload the class using Mockery and then change the implementation of the method.

$mock = \Mockery::mock('overload:'.HelperUtil::class);
$mock->shouldReceive('content')->andReturnUsing(function() {
    return 'different content';
});

这篇关于如何模拟其他类使用的全局函数和类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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