Define your own test case runner with reflection : Test Suite « JUnit « Java Tutorial






import java.lang.reflect.Method;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class TestSample extends TestCase {

  public TestSample(String name) {
    super(name);
  }

  public void setUp() {
  }

  public void tearDown() {
  }

  public void testMe() {
    assertTrue(true);
  }

  public static Test suite() {
    return new TestSuite(TestSample.class);
  }

  public static void main(String[] args) {
    TestFinder.run(TestSample.class, args);
  }

}

class TestFinder {

  public static void run(Class which, String[] args) {
    TestSuite suite = null;
    if (args.length != 0) {
      try {
        java.lang.reflect.Constructor ctor;
        ctor = which.getConstructor(new Class[] { String.class });
        suite = new TestSuite();
        for (int i = 0; i < args.length; i++) {
          suite.addTest((TestCase) ctor.newInstance(new Object[] { args[i] }));
        }
      } catch (Exception e) {
        System.err.println("Unable to instantiate " + which.getName() + ": " + e.getMessage());
        System.exit(1);
      }

    } else {
      try {
        Method suite_method = which.getMethod("suite", new Class[0]);
        suite = (TestSuite) suite_method.invoke(null, null);
      } catch (Exception e) {
        suite = new TestSuite(which);
      }
    }
    junit.textui.TestRunner.run(suite);
  }
}








39.3.Test Suite
39.3.1.Test suite
39.3.2.Per-Suite Setup and Tear-Down
39.3.3.Define your own test case runner with reflection
39.3.4.Use the test suite method