Skip to content

Instantly share code, notes, and snippets.

@kawahara
Created November 19, 2011 15:04
Show Gist options
  • Save kawahara/1378928 to your computer and use it in GitHub Desktop.
Save kawahara/1378928 to your computer and use it in GitHub Desktop.
mockery
<?php
// autoload
spl_autoload_register(function($name) {
require __DIR__.'/lib/'.$name.'.php';
});
<?php
// library は mockery/library
set_include_path(
__DIR__ . '/../../library'
. PATH_SEPARATOR . get_include_path()
);
require_once 'Mockery/Loader.php';
$loader = new \Mockery\Loader;
$loader->register();
require_once __DIR__.'/../autoload.php';
<?php
use \Mockery as M;
class PartialMockTest extends PHPUnit_Framework_TestCase
{
public function testPartialMock()
{
$mock = M::mock('Sample[bar]');
$mock->shouldReceive('bar')->andReturn('ばー');
// the method of sample's instance
$this->assertEquals('foo', $mock->foo());
// mocked method
$this->assertEquals('ばー', $mock->bar());
}
}
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="test/bootstrap.php"
>
<testsuite name="Starship Test Suite">
<directory>./test</directory>
</testsuite>
<listeners>
<listener class="\Mockery\Adapter\Phpunit\TestListener"
file="Mockery/Adapter/Phpunit/TestListener.php">
</listener>
</listeners>
</phpunit>
<?php
class Sample
{
public function foo()
{
return 'foo';
}
public function bar()
{
return 'bar';
}
public function sfoo()
{
return SampleSingleton::getInstance()->foo().' by SampleSingleton::foo()';
}
}
<?php
class SampleSingleton
{
static private $instance = null;
private function __construct()
{
}
static public function getInstance()
{
if (null === self::$instance)
{
self::$instance = new SampleSingleton();
}
return self::$instance;
}
public function foo()
{
return 'singleton foo';
}
}
<?php
use \Mockery as M;
class SingletonMockTest extends PHPUnit_Framework_TestCase
{
public function testSingletonClassMock() {
$mock = M::mock('alias:SampleSingleton');
$mock->shouldReceive('getInstance')->andReturn($mock);
$mock->shouldReceive('foo')->andReturn('しんぐるとんふー');
$sample = new Sample();
// Sample::sfoo() call SampleSingleton::foo()
// SampleSingleton::getInstance() and SampleSingleton::foo()
// is mocked by Mockery!
$this->assertEquals('しんぐるとんふー by SampleSingleton::foo()', $sample->sfoo());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment