'Class not found' when using namespaces in PHPUnit

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();

I had the same issue. I'm using composer as well and the only thing that solved it for me was the following:

  1. add to your composer.json file in the autoload section a class map section with your root namespace

    "autoload":  {
            "classmap": ["namespaceRoot/"]
    }
    
  2. execute composer dump-autoload command in order to recreate your autoload files (with all the class mappings!)