Naming Conventions – Naming Convention for Test Packages

namingpackages

We're actually naming our test packages just like their to-test counterparts. So we end up with this structure:

src/main/java
    com.hello.world
        helloWorld.java
src/test/java
    com.hello.world
        helloWorldTest.java

I always felt like this is not pretty smart since you can't distinguish between "test" and "to-test" if only provided with the package name. On the other hand I haven't really found a case where this matters somehow.
Is it a good practice to have the same naming conventions for both of the packages (for the test cases and the source classes)? If not, what would be a better approach?

Best Answer

That is a good convention.

Sometimes you want to write unit tests for package-private classes and methods also. You won't be able to call them from a unit test class placed in another package.

There shouldn't be any confusion about having unit test classes in the same namespace as they shouldn't be in the class path when compiling or running the production code.

Here's an example of a small module with a public interface, a public factory class and two package-private implementation classes:

src/main/java:
    com.hello.transmogrifier
        public interface Transmogrifier
        public class TransmogrifierFactory
        class MapTransmogrifier implements Transmogrifier
        class ListTransmogrifier implements Transmogrifier

scr/test/java:
    com.hello.transmogrifier
        public class TransmogrifierFactoryTest
        public class MapTransmogrifierTest
        public class ListTransmogrifierTest

Hiding the implementations of the Transmogrifier interface could be a valid design choice. Perhaps it's the responsibility of the factory class to choose the implementation.

Since the implementations are package-private, you need to place the unit test classes in the same package if you wish to test them directly. If you have your unit test classes in some other package, you only have direct access to the public interface and the factory class from your tests.

Related Topic