【发布时间】:2015-09-30 19:14:28
【问题描述】:
我们有以下简化的文件夹结构:
phpunit.xml
autoloading.php
index.php
/models
/user
user.php
...
/settings
preferences.php
...
/tests
test.php
这是相关文件的内容:
models/user/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;
}
}
自动加载.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,而不是 composer),它们也使用相同的自动加载机制:
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
知道我们必须改变什么以便自动加载在测试中也能正常工作吗?我们尝试了很多方法,但都行不通。
谢谢!
【问题讨论】:
标签: php namespaces phpunit autoload spl-autoload-register