如何使用我自己的自动加载器而不是Composer进行单元测试?

时间:2015-03-17 05:18:52

标签: php phpunit composer-php autoloader spl-autoload-register

phpunit.xml中的bootstrap是什么?如何使用我自己的自动加载器而不是Composer进行单元测试?

目录结构,

autoload/
Test/
vendor/
composer.json
phpunit.xml

原稿:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./Test/</directory>
        </testsuite>
    </testsuites>
</phpunit>

composer.json,

{
    "require": {
    },
    "require-dev": {
        "phpunit/phpunit": "*"
    },
    "autoload": {
        "psr-0": {
            "stats": ""
        }
    }
}

原始测试结果,

enter image description here

以下是我自己的自动加载课程autoload/ClassLoader.php

<?php
namespace MyVendor\Autoload;

class ClassLoader
{
    public function fetch( $directories ) 
    {
        spl_autoload_register( [$this, 'getClass'] );
    }

    private function getClass( $className )
    {
        ....
    }
}

我的phpunit.xml,我将bootsrap更改为autoload/ClassLoader.php

<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="autoload/ClassLoader.php">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./Test/</directory>
        </testsuite>
    </testsuites>
</phpunit>

当我在 CMD 中运行phpunit时,这是我的测试结果,

enter image description here

它看起来与原版不同,但并没有说它失败了。那么我的测试是否正确?

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

创建您自己的 bootstrap.php 文件,并使用spl_autoload_register注册自动加载器:

// External
spl_autoload_register('ClassLoader::getClass');

// Internal
function autoload($className)
{
....
}
spl_autoload_register('autoload');

然后在 phpunit.xml 文件中调用它:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="bootstrap.php">
   ...