Test Naming Conventions

Problem

You want to define a naming convention for your tests.

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.

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.[25] 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.

Tip

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>

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.



[25] 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.

Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.