1

My project's structure is:

--/
--src
--tests
--phpunit.xml
--composer.json

I want to use composer for autoloading my classes from src folder in tests. My composer.json:

{
"name": "codewars/pack",
"description": "Codewars project",
"type": "project",
"require": {
    "fxp/composer-asset-plugin": "^1.2.0",
    "phpunit/phpunit": "5.5.*",
    "phpunit/dbunit": "2.0.*"
},
"autoload": {
    "psr-4": {"Source\\": "src/"
    }
}

}

Autoloder files generated:

<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
'Source\\' => array($baseDir . '/src'),
);

My phpunit.xml:

<phpunit bootstrap="vendor/autoload.php">
<testsuites>
    <testsuite name="Tests">
        <directory>tests</directory>
    </testsuite>
</testsuites>
</phpunit>

And my test file example:

class Task2Test extends PHPUnit_Framework_TestCase
{
public function testTask2(){
    $list=[1,3,5,9,11];
    $this->assertEquals(7,\Source\findMissing($list));
    $list=[1,5,7];
    $this->assertEquals(3,\Source\findMissing($list));
 }

}

And when I run tests I get error such as Fatal error: Call to undefined function Source\findMissing()

Please, help me, how can I solve this problem?

1 Answers1

0

PSR-4 designed for autoloading classes, not for function. Because php cant find files with your functions.

May be better way write code with classes and static methods? Than you can use PSR-4 autoloading. Another way is specify "files" section into autoload section

{
    "name": "codewars/pack",
    "description": "Codewars project",
    "type": "project",
    "require": {
        "fxp/composer-asset-plugin": "^1.2.0",
        "phpunit/phpunit": "5.5.*",
        "phpunit/dbunit": "2.0.*"
},
"autoload": {
    "files": [
        "src/my_cool_function1.php",
        "src/my_cool_function2.php"
    ],
    "psr-4": {
        "Source\\": "src/"
    }
}

For more information see this question

Community
  • 1
  • 1
Bukharov Sergey
  • 9,767
  • 5
  • 39
  • 54