[ Team LiB ] Previous Section Next Section

4.11 Test Naming Conventions

4.11.1 Problem

You want to define a naming convention for your tests.

4.11.2 Solution

Prefix each test case classname with a consistent word, such as "Test" or "UnitTest". Put test cases in the same directory as the classes they are testing.

4.11.3 Discussion

Consistent naming conventions serve two purposes. First, they make your code more maintainable. Second, consistency facilitates automation. The tests in this chapter are prefixed with "Test", resulting in names like TestGame, TestPerson, and TestAccount. These correspond to the Game, Person, and Account classes, respectively.

Writing one test case per class makes it very easy to glance at a directory and see which tests are available. Putting "Test" at the beginning of the filenames makes sorting easier, in our opinion, particularly when your IDE provides some sort of jump-to functionality.[8] All tests will be grouped together and easy to identify. On the other hand, putting "Test" at the end of the filenames does make it easier to identify which classes do not have tests.

[8] IntelliJ IDEA (http://www.intellij.com) allows you to hit Ctrl-N and then begin typing a classname. If you follow the prefix convention, you immediately see a list of all tests as soon as you type Test.

Another popular convention is to place all test classes in a parallel directory structure. This allows you to use the same Java package names for your tests, while keeping the source files separate. To be honest, we do not like this approach because you must look in two different directories to find files. Ant can easily exclude tests from your build even if they reside in the same source directory.

Finally, a consistent naming convention makes it easier to locate tests when using Ant for your builds. You might want to exclude all of your tests when you create a production build of your software. You can do this in Ant as follows:

<javac destdir="${dir.build}">
  <src path="${dir.src}"/>
  <!-- see how easy it is to exclude the tests from a build! -->
  <exclude name="**/Test*.java"/>
</javac>

Prefix or Postfix?

We prefer to prefix "Test" onto the beginning of our test classnames, while many other people prefer to postfix "Test" onto the end. The main argument for postfixing names is that Customer.java and CustomerTest.java appear next to each other when sorting files within a directory. This makes it easy to identify which classes have tests.

We use the prefix convention because it makes searching easier within our IDE. We recommend you use the approach you prefer consistently. Remember that Ant relies on a consistent filenaming convention to locate tests.

4.11.4 See Also

Recipe 3.16 shows how to run tests using Ant based on naming conventions. Recipe 3.14 shows how to exclude test classes from a build.

    [ Team LiB ] Previous Section Next Section