1package junit.runner;
2
3import java.lang.reflect.*;
4import junit.runner.*;
5import 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 * {@hide} - Not needed for 1.0 SDK
13 */
14public class LoadingTestCollector extends ClassPathTestCollector {
15
16    TestCaseClassLoader fLoader;
17
18    public LoadingTestCollector() {
19        fLoader= new TestCaseClassLoader();
20    }
21
22    protected boolean isTestClass(String classFileName) {
23        try {
24            if (classFileName.endsWith(".class")) {
25                Class testClass= classFromFile(classFileName);
26                return (testClass != null) && isTestClass(testClass);
27            }
28        }
29        catch (ClassNotFoundException expected) {
30        }
31        catch (NoClassDefFoundError notFatal) {
32        }
33        return false;
34    }
35
36    Class classFromFile(String classFileName) throws ClassNotFoundException {
37        String className= classNameFromFile(classFileName);
38        if (!fLoader.isExcluded(className))
39            return fLoader.loadClass(className, false);
40        return null;
41    }
42
43    boolean isTestClass(Class 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 testClass) {
54        try {
55            testClass.getMethod(BaseTestRunner.SUITE_METHODNAME, new Class[0]);
56        } catch(Exception e) {
57            return false;
58        }
59        return true;
60    }
61
62    boolean hasPublicConstructor(Class testClass) {
63        try {
64            TestSuite.getTestConstructor(testClass);
65        } catch(NoSuchMethodException e) {
66            return false;
67        }
68        return true;
69    }
70}
71