我在框架项目中使用名称空间和PHP 5.3。我有主App
类和Autoloader
类。在App
类中,我设置了一些环境变量:
public static function setupEnv()
{
$os = 'UNIX';
if (stristr(PHP_OS,'WIN'))
{
$os = 'WIN';
}
if (!defined('DIRECTORY_SEPARATOR'))
{
define('DIRECTORY_SEPARATOR',($os == 'UNIX') ? '/' : '\\');
}
define('DS', \DIRECTORY_SEPARATOR);
if (!defined('PATH_SEPARATOR'))
{
define('PATH_SEPARATOR', ($os == 'UNIX') ? ':' : ';');
}
define('PS', \PATH_SEPARATOR);
if (!defined('APP_PATH'))
{
define('APP_PATH', dirname(dirname(__FILE__)));
define('AP', APP_PATH);
}
}
常量被正确定义,DIRECTORY_SEPARATOR
和DS
,如果我在这里回应它们就可以正常工作。这个名称空间是Feather \ App。在Autoloader
类中,我使用DS
常量,它只能正常工作。 Autoloader
类位于相同的Feather \ App名称空间中。
我正在运行PHPUnit,并创建了这个测试 - setupEnv()
在PHPUnit的setUp()
函数中调用:
public function testAutoloadFunction()
{
$this->assertEquals(
dirname(dirname(__FILE__)) . DS.'Components'.DS.'Collections'.DS.'Collection.php',
\Feather\App\Autoloader::Autoload('\\Feather\\Components\\Collections\\Collection')
);
}
即使路径正确返回,测试也会失败。它说:
Use of undefined constant DS - assumed 'DS'
所以这是一个很难回答我的问题 - 为什么这是一个错误?我想,好吧,也许我需要引用\ Feather \ App \ DS,但是这会抛出这个:
PHP Fatal error: Undefined constant 'Feather\App\DS' in /web/Feather/Tests/AutoloaderTest.php
我认为常量是在全球范围内定义的,所以不应该这样做吗?如果没有,我如何使这项工作,以便PHPUnit很高兴?如果我将use Feather\App
放在顶部,它仍然会失败并出现相同的assumed 'DS'
错误。
有人可以解释一下吗?到目前为止,PHP文档一直没有用!
答案 0 :(得分:0)
我遇到了一个非常类似的问题,并通过以下步骤运行测试:
1)使用@runInSeparateProcess
注释标记测试
2)在测试类中覆盖run()
,如下所示:
public function run(PHPUnit_Framework_TestResult $result = NULL) {
$this->setPreserveGlobalState(false);
return parent::run($result);
}
3)将导致在测试文件中定义常量的require_once()
放入setUp()
:
public function setUp() {
require_once __DIR__.'/SetUpEnv.php';
}
这可能不是一个理想的解决方法,但毫无疑问比没有解决方法更好。
我从StackOverflow和/或其他地方的其他答案中删除了一些碎片(或者整件事),但它已经有一段时间了,所以对我不在这里引用的来源道歉。
无论如何,希望这有帮助!