问题描述:

I'm new to PHPUnit and am having some trouble setting it up to access my PHP files. The directory structure I'm using for my app is this:

./phpunit.xml

./lib/Application/

-> Dir1/File1.php (namespace = Application\Dir1)

-> Dir1/File2.php

-> Dir2/File1.php (namespace = Application\Dir2)

./tests/Application/Tests

-> Test1.php (namespace = Application\Tests)

-> Test2.php

In my PhpUnit.xml, I have:

<?xml version="1.0" encoding="UTF-8"?>

<phpunit verbose="false">

<testsuites>

<testsuite name="Application">

<directory>./tests/Application/Tests</directory>

</testsuite>

</testsuites>

<logging>

<log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/>

<log type="json" target="/tmp/phpunit-logfile.json"/>

</logging>

<filter>

<whitelist>

<directory suffix=".php">./lib</directory>

</whitelist>

</filter>

</phpunit>

And in one of my test files, I open with:

namespace Application\Tests;

use Application\Dir1\File1;

class MyTest extends File1 {}

But it keeps on saying:

Class 'Application\Dir1\File1' not found

Where am I going wrong?

网友答案:

Even if you use use, you still have to include the file, either by using include, require, include_once, or require_once, or by using spl_autoload_register to include the file, like so:

spl_autoload_register(function ($class)
{
    include '\lib\\' . $class . 'php';
});

When you then try to use Application\Dir1\File1 the script will automatically run include '\lib\Application\Dir1\File1.php'

网友答案:

If you installed PHPUnit using Composer then you can use Composers autoloader. The easiest way to do so would be to add:

"autoload":{
    "psr-0":{
        "your-app-directory":""
    }
}

to composer.json

网友答案:

I found this really useful class autoloader by Jonathan Wage which allows PHPUnit tests to access namespaces from different directories. In my bootstrap.php, I just specified the location and associated module namespace:

require_once 'SplClassLoader.php';

$classLoader = new SplClassLoader('Application', dirname(__FILE__) . '/../lib');
$classLoader->register();
相关阅读:
Top