1. package junit.runner;
  2. import java.lang.reflect.*;
  3. import junit.runner.*;
  4. import junit.framework.*;
  5. /**
  6. * An implementation of a TestCollector that loads
  7. * all classes on the class path and tests whether
  8. * it is assignable from Test or provides a static suite method.
  9. * @see TestCollector
  10. */
  11. public class LoadingTestCollector extends ClassPathTestCollector {
  12. TestCaseClassLoader fLoader;
  13. public LoadingTestCollector() {
  14. fLoader= new TestCaseClassLoader();
  15. }
  16. protected boolean isTestClass(String classFileName) {
  17. try {
  18. if (classFileName.endsWith(".class")) {
  19. Class testClass= classFromFile(classFileName);
  20. return (testClass != null) && isTestClass(testClass);
  21. }
  22. }
  23. catch (ClassNotFoundException expected) {
  24. }
  25. catch (NoClassDefFoundError notFatal) {
  26. }
  27. return false;
  28. }
  29. Class classFromFile(String classFileName) throws ClassNotFoundException {
  30. String className= classNameFromFile(classFileName);
  31. if (!fLoader.isExcluded(className))
  32. return fLoader.loadClass(className, false);
  33. return null;
  34. }
  35. boolean isTestClass(Class testClass) {
  36. if (hasSuiteMethod(testClass))
  37. return true;
  38. if (Test.class.isAssignableFrom(testClass) &&
  39. Modifier.isPublic(testClass.getModifiers()) &&
  40. hasPublicConstructor(testClass))
  41. return true;
  42. return false;
  43. }
  44. boolean hasSuiteMethod(Class testClass) {
  45. try {
  46. testClass.getMethod(BaseTestRunner.SUITE_METHODNAME, new Class[0]);
  47. } catch(Exception e) {
  48. return false;
  49. }
  50. return true;
  51. }
  52. boolean hasPublicConstructor(Class testClass) {
  53. try {
  54. TestSuite.getTestConstructor(testClass);
  55. } catch(NoSuchMethodException e) {
  56. return false;
  57. }
  58. return true;
  59. }
  60. }