Create a gist now

Instantly share code, notes, and snippets.

A Testing Object for Singleton Pattern written in PHP
<?php
/**
* Empty Singleton Class
*
* @since 2010-09-19
* @require PHP >= 5.0.0
*/
class Singleton {
private function __construct() {
}
function instance() {
static $obj;
if ( !$obj ) {
$obj = new Singleton();
}
return $obj;
}
}
<?php
/**
* SingletonTestCase
*
* @since 2010-09-19
* @require PHP >= 5.2.0
*/
/** UnitTestCase */
require_once( 'Pearified/Testing/SimpleTest/unit_tester.php' );
/** SimpleReporter */
require_once( 'Pearified/Testing/SimpleTest/reporter.php' );
/** Singleton */
require_once( dirname( __FILE__ ).'/singleton.php' );
class TestingSingleton extends Singleton {
public function __construct() {
}
function instance() {
return new TestingSingleton();
}
}
/**
* SingletonTestCase
*
* @since 2010-09-19
*/
class Test_Singleton extends UnitTestCase {
function Test_Singleton() {
}
function test_instance() {
$obj1 = Singleton::instance();
$obj2 = Singleton::instance();
$this->assertEqual( spl_object_hash( $obj1 ), spl_object_hash( $obj2 ) );
}
function test_fakeinstance() {
$this->assertTrue( is_object( new TestingSingleton() ) );
$obj1 = TestingSingleton::instance();
$obj2 = TestingSingleton::instance();
$this->assertFalse( spl_object_hash( $obj1 ) == spl_object_hash( $obj2 ) );
}
}
if ( realpath( $_SERVER['SCRIPT_FILENAME'] ) == __FILE__ ) {
$test = new Test_Singleton();
$reporter = null;
if ( SimpleReporter::inCli() ) {
$reporter = new TextReporter();
} else {
$reporter = new HtmlReporter();
}
exit( $test->run( $reporter ) ? 0 : 1 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment