【发布时间】:2015-07-30 05:42:53
【问题描述】:
我有一个项目尝试运行单元测试但没有成功。很可能与自动加载有关。
/path/to/project$ phpunit 测试
致命错误:在 /path/tests/Foo/BarTest.php 中找不到类 'Foo\Bar' X线
这一行是执行 new Bar();
我在测试目录中有一个 phpunit.xml,像这样
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="../tests/bootstrap.php"
backupGlobals="false"
backupStaticAttributes="false"
verbose="true">
<testsuites>
<testsuite name="App">
<directory suffix="Test.php">tests/Foo</directory>
</testsuite>
</testsuites>
<logging>
<log type="coverage-html" target="build/coverage"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<log type="coverage-crap4j" target="build/logs/crap4j.xml"/>
<log type="junit" target="build/logs/junit.xml" logIncompleteSkipped="false"/>
</logging>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
<exclude>
<file>src/bootstrap.php</file>
</exclude>
</whitelist>
</filter>
</phpunit>
我的结构是 src/Foo/Bar.php 测试/Foo/BarTest.php
我的测试/bootstrap.php
if ( ! file_exists($file = __DIR__.'/../vendor/autoload.php')) {
throw new RuntimeException('Install dependencies to run this script.');
}
$loader = require_once $file;
$loader->add('Foo', __DIR__ . '../src/');
所以我将 Foo 命名空间映射到 src 目录,但 PHPUnit 似乎找不到它。
这个自动加载是 Composer 生成的。
【问题讨论】:
-
如果您尝试从 bootstrap.php 实例化类会发生什么?您是否使用 Bar 的完全限定名称?也许命名空间被认为是相对于测试命名空间...
-
那么 BarTest.php 上的代码提到使用 Foo\Bar;在违规行我使用 new Bar();所以不需要指定完全限定的。
标签: php phpunit autoloader