Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock global functions and classes used by another class

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

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.

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

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?

Thanks

like image 503
Damien Walsh Avatar asked Dec 18 '22 09:12

Damien Walsh


1 Answers

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';
});
like image 80
OnIIcE Avatar answered Jan 05 '23 19:01

OnIIcE