Skip to content

Instantly share code, notes, and snippets.

@davidrjonas
Created February 3, 2017 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidrjonas/a514bde5f3be030b6a762edacc12dd2e to your computer and use it in GitHub Desktop.
Save davidrjonas/a514bde5f3be030b6a762edacc12dd2e to your computer and use it in GitHub Desktop.
Using PHP namespaces to mock functions
<?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