Using suites for test categories

During a hip presentation in Boston, I was reminded that one can simulate test groups via JUnit’s test suite mechanism. While I tend not to use suites due to copacetic runners in Ant and Maven, the technique is certainly applicable and for some, it’s more convenient. Plus, by using test suites, one doesn’t need to worry about naming patterns or directory structures (that is, until they need a way to segregate the suites themselves). On the downside, of course, the problem with suites is that they are inherently a manual process– one must add new tests to them pragmatically.

For example, I can define a suite of component tests as follows:

package test.org.acme.widget;

import junit.framework.Test;
import junit.framework.TestSuite;
import test.org.acme.widget.dao.*;

public class ComponentTestSuite {

 public static void main(String[] args){
  junit.textui.TestRunner.run(ComponentTestSuite.suite());
 }

 public static Test suite(){
  TestSuite suite = new TestSuite();
  suite.addTestSuite(SpringWidgetDAOImplTest.class);
  suite.addTestSuite(WidgetFinderTest.class);
  suite.addTestSuite(UserWidgetTest.class);
  suite.addTestSuite(WidgetAccessTest.class);
  return suite;
 }
}

The ComponentTestSuite class defines a suite method, which will reflectively add all tests in the four test classes added in the addTestSuite methods. Therefore, when this class is executed (either via Ant, Maven, the command line, or even TestNG) all component tests are run. Note, if a new component test class is defined, it must be added in this class’s suite method (which requires a recompile).

Interestingly, the JUnit-addons and GSBase projects have some dynamic APIs, which facilitate auto-discovering JUnit tests in directories; however, because it’s my bag, I’d argue that you may be better served by following a directory naming pattern and relying on Ant’s junit task to do the same. Do you dig it, man?

Related odds and ends
 

2 Responses to “Using suites for test categories”

  1. on 16 Oct 2006 at 6:14 pm x

    The problem with this approach is that classes are still constrained to belong to only one package, a problem that TestNG solves cleanly by using groups and letting test methods belong to as many groups as they want…

  2. on 16 Oct 2006 at 8:09 pm Andy

    I agree! The funny thing is that I was giving a presentation on TestNG and a participant mentioned this mechanism with JUnit suites.

Trackback this Post | Feed on comments to this Post

Leave a Reply