KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > junit > runner > LoadingTestCollector


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

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