Interview Questions

How Do You Run All Test Classes without Managing a TestSuite Explicitly?

JUnit Questions and Answers


(Continued from previous question...)

How Do You Run All Test Classes without Managing a TestSuite Explicitly?

To run all test classes, usually we need to:

  • Create a separate class named like AllTests.java.
  • Create a suite() to return a TestSuite object.
  • Add all test classes into the TestSuite object.
  • Run AllTests.java with a test runner.

But you can also organize all test classes in a TestSuite automatically and not use or manage a TestSuite explicitly. There are a number of ways to do this:

1. In Ant, use the junit task and the batchtest element: The approach requires that idiomatic naming patterns for unit tests: Test*.java and *Test.java.

<junit printsummary="yes" haltonfailure="yes">
  ...
  <batchtest fork="yes">
    <fileset dir="${src.dir}">
       <include name="**/*Test.java" />
       <include name="**/Test*.java" />
     </fileset>
  </batchtest>
</junit>

2. Use the DirectorySuiteBuilder and ArchiveSuiteBuilder (for jar/zip files) classes provided by JUnit-addons project. Documentation and examples are at http://junit-addons.sourceforge.net.

DirectorySuiteBuilder builder = new DirectorySuiteBuilder();
builder.setSuffix("Test");
Test suite = builer.suite("/home/project/myproject/tests");

3. Write your own custom suite builder. Have your test classes implement an interface and write a treewalker to load each class in a directory, inspect the class, and add any classes that implement the interface to a TestSuite.

You might only want to do this if you are very uncomfortable with using a naming convention for test classes. Aside from being slow for larger suites, ultimately it's arguable whether it's more effort to follow a naming convention that have test classes implement an interface!

(Continued on next question...)

Other Interview Questions