Composer cannot load loader when PhpUnit is used
Asked Answered
I

1

3

I am trying to use PhpUnit with Composer. In this purpose I did:

1 Added phpunit to req composer section:

"require": {
    "php": ">=5.3.0"
},
"require-dev": {
    "phpunit/phpunit": "3.7.*"
},
"autoload": {
    "psr-0": {"PhpProject": "src/"}
}

2 Installed what needed:

php composer.phar install --dev

Operation finished with success.

Installing phpunit/phpunit (3.7.6) Downloading: 100%

Unfortunately when I want to run the tests, I get

./vendor/bin/phpunit PHP Fatal error: Call to a member function add() on a non-object in /home/serek/php/project/tests/bootstrap.php on line 12

Problem occurs because return ComposerAutoloaderInit::getLoader(); in vendor/autoload returns NULL into test bootstrap.

Any idea how can it be solved without hacking Loader?

Code: phpunnit.xml.dist

> <?xml version="1.0" encoding="UTF-8"?>
> 
> <phpunit bootstrap="tests/bootstrap.php" colors="true">
>     <testsuites>
>         <testsuite name="PhpProject Test Suite">
>             <directory>tests/PhpProject/</directory>
>         </testsuite>
>     </testsuites>
> 
>     <filter>
>         <whitelist>
>             <directory suffix=".php">src/PhpProject/</directory>
>         </whitelist>
>     </filter> </phpunit>

tests/bootstrap.php (here I need only autoloader)

> $loader = require_once __DIR__ . "/../vendor/autoload.php";
> $loader->add('PhpProject\\', __DIR__); //<- this is problematic line 12 (comments has 9 lines) 

/../vendor/autoload.php

// autoload.php generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit::getLoader();
Insincere answered 8/10, 2012 at 23:1 Comment(4)
You are talking about a code fragment that you do not share, adding it to the question might make this easier to understand for others.Photodrama
Obviously your test bootstrap throws the error, but you do not show us the code. Might be your assumptions are wrong.Oppressive
some file content is attached nowInsincere
No idea if that is your issue, but require_once and return values does not make much sense, it perhaps should be require. Also ensure the file is actually returning something.Photodrama
P
11

The issue is that PHPUnit already requires the autoload file, so your require_once call is not executed and therefore the return value is not set (php doesn't keep the return value of require calls so require_once breaks on that use case).

You can safely change it to a require because with recent composer versions the autoloader is not created twice anymore and requiring it many times just returns you the same instance every time.

Patnode answered 9/10, 2012 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.