【问题标题】:Fatal error: Class 'Foo\Bar' not found in /path/tests/Foo/BarTest.php on line X致命错误:在第 X 行的 /path/tests/Foo/BarTest.php 中找不到类 'Foo\Bar'
【发布时间】: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


【解决方案1】:

我发现了问题。由于路径问题,PHPUnit 没有找到引导程序,因此没有加载 Composer 自动加载。

因为它没有显示任何隐藏实际问题的警告。

因此,假设您要从测试文件夹中运行测试,您应该像这样指向您的 phpunit.xml

测试/phpunit.xml

<phpunit bootstrap="bootstrap.php" ...

所以 bootstrap.php 也应该在测试文件夹中。

【讨论】:

    猜你喜欢
    • 2022-11-04
    • 2017-07-25
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    相关资源
    最近更新 更多