0
votes

I have a project for which I am trying to run unit tests without success. It is most likely to be related to the autoload.

/path/to/project$ phpunit tests

Fatal error: Class 'Foo\Bar' not found in /path/tests/Foo/BarTest.php on line X

This line is the one that does the new Bar();

I have a phpunit.xml inside the tests directory like this

<?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>

My structure is src/Foo/Bar.php tests/Foo/BarTest.php

My tests/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/');

So I am mapping the Foo namespace to the src directory but PHPUnit seems to not find it.

This autoload is the Composer generated one.

1
what happens if you try to instantiate the class from bootstrap.php? Are you using fully qualified name for Bar? maybe the namespace is being taken as relative to the test namespace... - gontrollez
Well the code on the BarTest.php mentions use Foo\Bar; and on the offending line I use new Bar(); so there is no need to specify the fully qualified one. - bicatu

1 Answers

0
votes

I found the issue. PHPUnit was not finding the bootstrap due to a path issue and because of that did not load the Composer autoload.

Since it did not show any warning that shadowed the real problem.

So assuming you are going to run the tests from within the tests folder you should point your phpunit.xml like this

tests/phpunit.xml

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

so bootstrap.php should be inside tests folder as well.