为什么命名空间自动加载类没有在 phpunit 测试中加载?
为了补充 phpunit、autoload 和命名空间之间现有的大杂烩,
我创建了一个简单的测试项目,它运行 PhpUnit 测试并使用命名空间自动加载。我在引导文件中注册自动加载,如下所示:
set_include_path(get_include_path() . PATH_SEPARATOR . "/path/to/classes/folder");
spl_autoload_register();
在单元测试中,我加载并测试我的类,如下所示:
$obj = new \some\space\someClass(); // which is in the classes/some/space folder
$this->assertTrue($obj->foo()=='bar');
我收到错误
致命错误:在 testSomeClass.php 中找不到类“\some\space\someClass”...
To compliment an existing smorgasbord of arrangements between phpunit,autoload and namespace is this:
I have created a simple test project that runs PhpUnit tests and uses namespace autoloading. I register the autoloading in the bootstrap file like so:
set_include_path(get_include_path() . PATH_SEPARATOR . "/path/to/classes/folder");
spl_autoload_register();
and inside a unit test I load and test my class like so:
$obj = new \some\space\someClass(); // which is in the classes/some/space folder
$this->assertTrue($obj->foo()=='bar');
And I get an error
Fatal error: Class '\some\space\someClass' not found in testSomeClass.php...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然这不是特定于 phpunit 的,但您需要更改为:
注册
自动加载器的任何其他组件都会取消注册默认的
__autoload()
。这就是
spl-autoload
与其他使用自动加载。While this is not phpunit specific you need to change:
to
Any other component that registers an autoloader unregisters the default
__autoload()
.So this is how
spl-autoload
works together with anything else that uses autoloading.确保类文件夹的路径相对于为测试执行而运行的脚本。如果脚本位于项目的子文件夹中(例如
tests/
),那么您的路径应该是../path/to/classes/folder
这就是我的路径
测试/bootstrap.php
Make sure your path to classes folder is made relative to script which is run for tests execution. If the script is in subfolder of your projects (for example
tests/
) then your path should be../path/to/classes/folder
That's what I have in my
tests/bootstrap.php