Reputation: 29260
I have the following project structure
src/
├─ MyPackage/
├─ MySDK.php
└─ SDKHelper.php
test/
├─ MySDKTest.php
└─ TestUtils.php
composer.json
composer.lock
My composer.json file looks like this:
"autoload": {
"psr-4": {
"MyPackage\\": "src/MyPackage"
}
}
Everything worked great, and MySDKTest.php
unit tests were passing, until I tried adding some utility methods to a third file, TestUtils.php
. When I try to call TestUtils::utilityMethod()
from MySDKTest.php
, phpunit complains that the class TestUtils
is not found.
I've been reading about adding an autoload-dev key, variations whereof I have tried, but so far, it appears that nothing is working. I should clarify that I am able to use MySDK
and SDKHelper
methods inside MySDKTest
. MySDKTest.php
looks like this when it works:
use MyPackage\MySDK;
class MySDKTest extends PHPUnit_Framework_TestCase {
public function testPackage() {
$sdk = new MySDK();
$sdk->exampleMethod();
}
}
Upvotes: 1
Views: 1241
Reputation: 17292
It should be pretty simple. Composer's PSR-4 autoloader just defines a mapping from a namespace to a folder.
Are your tests namespaced correctly? It looks like they're not since you have a use
at the top of your test class. If MySDK
is in the namepace MyPackage
(fully qualified MyPackage\MySDK
), I would expect MySDKTest
to also be in the MyPackage
namespace at MyPackage\MySDKTest
. It doesn't have to be that way - you could put the tests in a different namespace if you prefer.
Regardless, the reason it's not working is you didn't register the test folder with the autoloader. The way it looks like your stuff is currently set up, your autoloader config should look like this:
{
"autoload": {
"psr-4": { "MyPackage\\": ["src/MyPackage/", "test/"] }
}
}
Also you'd need to change use MyPackage\MySDK;
to namespace MyPackage;
in your test class.
Note
Your folder structure is a little weird. I would expect test
to match src
. So it would be like this:
test/
├─ MyPackage/
├─ MySDK.php
└─ SDKHelper.php
Adjust the namespace accordingly:
{
"autoload": {
"psr-4": { "MyPackage\\": ["src/MyPackage", "test/MyPackage"] }
}
}
Upvotes: 1