Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Unit Tests: should tests be under the same namespace as the class?

The Symfony 2.0 bundle directory structure, conventionally, has a Tests directory where tests should be placed.

Acme
    -> SomeBundle
        -> Controller
        -> Entity
        -> Service
        -> ...
        -> Tests
            -> Controller
            -> Entity
            -> Service
            -> ...
    -> OtherBundle
    -> ...

I am aware the tests work even if they are not under the same namespace as the classes they test.

namespace Acme\SomeBundle\Service;

/**
 * Some service.
 *
 * @author varchar
 * @since  August 1, 2012
 */
class SomeService
{
}

For the class above, I (for one) would usually have a test under the following name space (as influenced by the directory structure):

namespace Acme\SomeBundle\Tests\Service;

Now, this works okay.

Incidentally however, I use the Netbeans IDE which cannot find a test class unless it is under the same namespace (this is notable when you want to test only a single file). Well, this could be just a Netbeans standard (or something).

Regardless however, is it appropriate to put tests under the same namespace as the class being tested? Are there any merits in doing so?

Question

1) Is it appropriate to put tests under the same namespace as the class being tested?

2) Are there any merits in doing so?

like image 209
Czar Pino Avatar asked Aug 01 '12 02:08

Czar Pino


2 Answers

Is it appropriate to put tests under the same namespace as the class being tested?

So far, there have been no issues regarding about this. So this would, perhaps, only be a matter personal preference, for now.

Are there any merits in doing so?

It seems there are.

1) Since the test and the class will be sharing the same namespace, no need for

use Acme\SomeBundle\Tests\Service

in the test class. In other words, it is slightly more convenient to create a test sharing the same namespace as the class.

2) If you are using NetBeans then you will be able to run a test on a single class using the IDE.

like image 91
Czar Pino Avatar answered Nov 16 '22 11:11

Czar Pino


In Bundles this is so that the package you get will have all the tests as well so you can run them. This is the same with the Symfony Components because they are selfcontained packages aswell. Mostly it depends on your style. Another common pattern is like github.com/vandpibe/security

like image 34
Henrik Bjørnskov Avatar answered Nov 16 '22 11:11

Henrik Bjørnskov