PHPUnit - autoloader test class

I need to create an autoloader for my application. I don’t want to depend on a file in the file system, so how do I make fun of a new call? Or how do you test the autoloader class? Thank.

+5
source share
3 answers

Or how do you check the autoloader class

IMHO you do not need unit test your autoloader.

If you download your application, it will work hard because it will find all the necessary classes or your autoloader will work fine.

, " ", , .

, " ", , , .

, , require/include , .

+4

, , ( ), . class_exists($class, false), , .

.. , , .

autoload() :

function test_autoload_loadsExistingClass() {
    $this->fixture->registerPrefix('TestClasses', self::$root . 'models');
    if (class_exists('TestClasses_Autoloader_Foo', false)) {
        self::error('Class TestClasses_Autoloader_Foo is already loaded');
    }
    $this->fixture->autoload('TestClasses_Autoloader_Foo');
    if (!class_exists('TestClasses_Autoloader_Foo', false)) {
        self::fail('Class TestClasses_Autoloader_Foo failed to load');
    }
}

function test_autoload_silentlyIgnoresMissingClasses() {
    $this->fixture->registerPrefix('Foo', self::$root . 'models');
    $this->fixture->autoload('Foo_Bar');
}

function test_autoload_searchesIncludePathForUnknownPrefix() {
    if (class_exists('TestClasses_Autoloader_Foo', false)) {
        self::error('Class TestClasses_Autoloader_Foo is already loaded');
    }
    set_include_path(self::$root . 'include' . PATH_SEPARATOR . self::$savedIncludePath);
    $this->fixture->autoload('TestClasses_Autoloader_Foo');
    if (!class_exists('TestClasses_Autoloader_Foo', false)) {
        self::fail('Class TestClasses_Autoloader_Foo failed to load');
    }
}

: , , " " , . include (, includeFile($path)). , . , : ( ) , , , includeFile() , .

function testAutoloadLoadsExistingClass() {
    $fixture = $this->getMock('MyAutoloader', 
            array('includeFile'),  // mock the call to `include`
            array(...));           // constructor args
    $fixture->expects($this->once())
            ->method('includeFile')
            ->with('My/Package/Class')
            ->will($this->returnValue(true));
    self::assertTrue($fixture->autoload('My_Package_Class'));
}
+1

?

, . , , spl_autoload_register.

Or, if your autoloader provides a function LoadLibrarythat loads all the classes and interfaces of your library to check if all classes have been loaded. But it usually depended on the file system (which, I think, is okay).

0
source

All Articles