KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > junit > runner > LoadingClassPathTestCollector


1 package junit.runner;
2
3 import java.lang.reflect.*;
4 import junit.runner.*;
5 import junit.framework.*;
6
7 /**
8  * An implementation of a TestCollector that loads
9  * all classes on the class path and tests whether
10  * it is assignable from Test or provides a static suite method.
11  * @see TestCollector
12  */

13 public class LoadingClassPathTestCollector extends ClassPathTestCollector {
14     
15     TestCaseClassLoader fLoader;
16     
17     public LoadingClassPathTestCollector() {
18         fLoader= new TestCaseClassLoader();
19     }
20     
21     protected boolean isTestClass(String JavaDoc classFileName) {
22         try {
23             if (classFileName.endsWith(".class")) {
24                 Class JavaDoc testClass= classFromFile(classFileName);
25                 return (testClass != null) && isTestClass(testClass);
26             }
27         }
28         catch (ClassNotFoundException JavaDoc expected) {
29         }
30         catch (NoClassDefFoundError JavaDoc notFatal) {
31         }
32         return false;
33     }
34     
35     Class JavaDoc classFromFile(String JavaDoc classFileName) throws ClassNotFoundException JavaDoc {
36         String JavaDoc className= classNameFromFile(classFileName);
37         if (!fLoader.isExcluded(className))
38             return fLoader.loadClass(className, false);
39         return null;
40     }
41     
42     boolean isTestClass(Class JavaDoc testClass) {
43         if (hasSuiteMethod(testClass))
44             return true;
45         if (Test.class.isAssignableFrom(testClass) &&
46             Modifier.isPublic(testClass.getModifiers()) &&
47             hasPublicConstructor(testClass))
48             return true;
49         return false;
50     }
51     
52     boolean hasSuiteMethod(Class JavaDoc testClass) {
53         try {
54             Method suiteMethod= testClass.getMethod(BaseTestRunner.SUITE_METHODNAME, new Class JavaDoc[0]);
55         } catch(Exception JavaDoc e) {
56             return false;
57         }
58         return true;
59     }
60     
61     boolean hasPublicConstructor(Class JavaDoc testClass) {
62         Class JavaDoc[] args= { String JavaDoc.class };
63         Constructor c= null;
64         try {
65             c= testClass.getConstructor(args);
66         } catch(Exception JavaDoc e) {
67             return false;
68         }
69         return true;
70     }
71
72 }
73
Popular Tags