Interview Questions

Where Should You Place Test Classes?

JUnit Questions and Answers


(Continued from previous question...)

Where Should You Place Test Classes?

You should consider two points when answering this question:

  • Test classes must share the same package name as the test target classes. This is needed to allow a test class to access "protected" items in a target class.
  • The source files of test classes should not be packaged together with target classes to be delivered as the final product.

The first approach is to place your test classes in the same source directory directory as test target classes:

    src
       com
          xyz
             SomeClass.java (target class)
             SomeClassTest.java	(test class)

While adequate for small projects, many developers feel that this approach clutters the source directory, and makes it hard to package up client deliverables without also including unwanted test code, or writing unnecessarily complex packaging tasks.

An arguably better appoach is to create a new source directory named as "test". All test classes are placed in the "test" source directory with the same packaging structure as target classes:

    src
       com
          xyz
             SomeClass.java (target class)
    test
       com
          xyz
             SomeClassTest.java	(test class)

This approach allows test classes to access to all the public and package visible methods of target classes.

(Continued on next question...)

Other Interview Questions