PHPUnit无法通过命名空间自动加载找到类

时间:2015-07-12 12:39:02

标签: php namespaces phpunit autoload spl-autoload-register

我们有以下简化的文件夹结构:

phpunit.xml
autoloading.php
index.php

/models
    /user
        user.php
        ...

    /settings
        preferences.php
        ...

/tests
    test.php

这是相关文件的内容:

模型/用户/ user.php的

namespace models\user;

class User {

    private $preferences;

    public function __construct()
    {
        $this->preferences = new \models\settings\Preferences();
    }

    public function getPreferenceType()
    {
        return $this->preferences->getType();
    }
}

模型/设置/ preferences.php

namespace models\settings;

class Preferences {

    private $type;

    public function __construct($type = 'default')
    {
        $this->type = $type;
    }

    public function getType()
    {
        return $this->type;
    }
}

autoloading.php

spl_autoload_extensions('.php');
spl_autoload_register();

的index.php

require_once 'autoloading.php';

$user = new \models\user\User();
echo $user->getPreferenceType();

当我们运行index.php时,一切都可以自动通过命名空间自动加载。由于命名空间符合文件夹结构,因此所有内容都会自动加载。

我们现在想设置一些PHPUnit测试(通过phpunit.phar,而不是编写器),它们也使用相同的自动加载机制:

phpunit.xml

<phpunit bootstrap="autoloading.php">
    <testsuites>
        <testsuite name="My Test Suite">
            <file>tests/test.php</file>
        </testsuite>
    </testsuites>
</phpunit>

测试/ test.php的

class Test extends PHPUnit_Framework_TestCase
{
    public function testAccess()
    {
        $user = new \models\user\User();
        $this->assertEquals('default', $user->getPreferenceType());
    }
}

但是,当我们运行测试时,会出现以下错误:

Fatal error: Class 'models\user\User' not found in tests\test.php on line 7

我们当然可以在测试中添加以下方法:

public function setup()
{
    require_once '../models/user/user.php';
}

然后会发生以下错误,等等:

Fatal error: Class 'models\settings\Preferences' not found in models\user\user.php on line 11

知道我们必须改变什么,以便自动加载在测试中也能工作吗?我们已经尝试了很多东西,但它不起作用。

谢谢!

1 个答案:

答案 0 :(得分:3)

我们找到了解决问题的方法:

我们现在使用 psr-4通过composer 进行自动加载,而不是使用我们自己的autoloading.php文件(见上文)。我们的composer.json文件如下所示:

{
  "autoload": {
    "psr-4": {
      "models\\": "models/"
    }
  }
}

在触发composer install后,正在创建包含vendor的新文件夹autoload.php。 index.php以及phpunit.xml(<phpunit bootstrap="vendor/autoload.php">)中可能需要此文件。

通过这种自动加载设置(同时仍使用相同的名称空间),一切都可以无缝运行。

相关问题