Created
February 3, 2017 03:28
-
-
Save davidrjonas/a514bde5f3be030b6a762edacc12dd2e to your computer and use it in GitHub Desktop.
Using PHP namespaces to mock functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Define the function in the namespace that the caller is in. | |
namespace App { | |
function query() { | |
return call_user_func_array([$GLOBALS['__doubles']['query'], 'call'], func_get_args()); | |
} | |
} | |
namespace Tests { | |
// Create a basic interface we can mock | |
interface FunctionProxy { public function call(); } | |
class ServiceTest extends \PHPUnit_Framework_TestCase | |
{ | |
public function testSomething() | |
{ | |
$mock = $this->prophesizeFunction('query'); | |
$mock->call('SELECT * FROM users')->shouldBeCalled()->willReturn('foo'); | |
$this->assertEquals('foo', (new \App\Service)->users()); | |
} | |
private function prophesizeFunction($name) | |
{ | |
$double = $this->prophesize(FunctionProxy::class); | |
$GLOBALS['__doubles'][$name] = $double->reveal(); | |
return $double; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment