Accepted answer

While there is no only right way, the usual approach is to keep unit tests in the same project.

You can create a second source folder (like test), where you put your test classes into the same packages as the classes under test. This also allows you to test package-private classes while not flooding your main source packages with test classes.

Your source folder/package structure would then look like this:


You can then configure your build to not include the test source folder when packing the JAR.


Consider the maven way : In a maven project, soruces are organized this way

 |     |--java

Your source code goes in src/main/java, your junit test code goes in src/test/java, they both are source folder (and as a consequence you can put your jUnit code in the same package as your Java code, but in a different source folder).

The interest is that for usual coding, your jUnit classes are in code packages, but on jar creation, you can take classes coming only from src/main/java and not release your tests.


Typically you have -

/src/main/java   (for codes)

/src/test/java   (for tests)


I like the maven convention a lot: There is a separate source tree for main and test in the same project, main code gets deployed, test code doesn't. Package structures can be (but don't have to be) identical.

             java      // source files
             resources // xml, properties etc
             java      // source files
             resources // xml, properties etc

And in eclipse, when you choose new -> JUnit test case, you just change the source folder to src/test/java and leave the suggested package as is.

(One of the benefits of remaining in the same package is having access to protected and package scoped members, although this is not 'proper' unit test behavior)

Update: Here's some code to illustrate my last point:

Main class (in src/main/java):

package com.test;
public class Foo{

    static class Phleem{
        public Phleem(final String stupidParameter){

    String bar;
    protected String baz;
    protected Object thingy;


Test class (in src/test/java):

package com.test;
import org.junit.Test;

public class FooTest{

    public void testFoo(){
        final Foo foo = new Foo(); = "I can access default-scoped members";
        foo.baz = "And protected members, too";
        foo.thingy = new Foo.Phleem("And I can access default-scoped classes");


Related Query

More Query from same tag