This question is about handling namespaces and unit testing in ZF2.
Let’s say I have a module called Application
. I have constructed composer.json
to be like so
"autoload":{
"psr-4": {
"Application\" : ["module/Application/src", "module/Application"],
}
}
where first path is for the main code in the src
folder as per PSR-4, and the second path is used access test
namespace.
What I get then is this directory structure:
module
/Application
/public
/src
/Form
Form.php //namespace ApplicationForm;
/test
/Form
FormTest.php //namespace ApplicationtestForm
/test
/Form
FormTest.php //namespace ApplicationtestForm;
This works, and seems to work both in Zend Studio, and in PHP-CLI (command line). For FormTest.php
class, the one in src
gets priority despite both of them being in the same namespace. I put them both just for an example that I can use either location.
Question: I am concerned that having two paths in composer causes extra work for class name resolver, i.e when class is not found cleanly, in src
, ZF2 does a lookup in test
.
Can I improve the code? Do I best use the src
namespace only and move my test
into src/test
directory and namespace? That is, get rid of module/Application/test
folder and keep module/Application/src/test
? IS there a recommended best practices for this?
1
I usually keep tests
and src
completely independent, and not nested under each other.
Sources and test sources are typically defined like that.
In an application, I usually have following:
module
/Application
...
/src
/Form
Form.php // ApplicationFormForm
/test
/unit
/Form
FormTest.php // ApplicationUnitTestFormFormTest
/integration
/Form
FormTest.php // ApplicationIntegrationTestFormFormTest
tests
/e2e
/web
...
LoginSeleniumTest.php // E2EWebTestLoginSeleniumTest
Specifically, only unit tests are allowed inside modules. In some rare cases, I have a integration tests, but they should really be avoided as well as annotated with @coversNothing
.
I adjust the composer.json
to autoload each of these namespaces:
{
"autoload": {
"psr-4": {
"Application\": "module/Application/src"
}
},
"autoload-dev": {
"psr-4": {
"ApplicationUnitTest\": "module/Application/test/unit",
"ApplicationIntegrationTest\": "module/Application/test/integration",
"E2EWebTest\": "tests/e2e/web"
}
}
}
What the IDE says here is completely irrelevant.