summaryrefslogtreecommitdiff
path: root/dx/src/junit/runner/LoadingTestCollector.java
blob: b1383593051b12d204031b1a3d27e4fad54285b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package junit.runner;

import java.lang.reflect.*;
import junit.runner.*;
import junit.framework.*;

/**
 * An implementation of a TestCollector that loads
 * all classes on the class path and tests whether
 * it is assignable from Test or provides a static suite method.
 * @see TestCollector
 */
public class LoadingTestCollector extends ClassPathTestCollector {
	
	TestCaseClassLoader fLoader;
	
	public LoadingTestCollector() {
		fLoader= new TestCaseClassLoader();
	}
	
	protected boolean isTestClass(String classFileName) {	
		try {
			if (classFileName.endsWith(".class")) {
				Class testClass= classFromFile(classFileName);
				return (testClass != null) && isTestClass(testClass);
			}
		} 
		catch (ClassNotFoundException expected) {
		}
		catch (NoClassDefFoundError notFatal) {
		} 
		return false;
	}
	
	Class classFromFile(String classFileName) throws ClassNotFoundException {
		String className= classNameFromFile(classFileName);
		if (!fLoader.isExcluded(className))
			return fLoader.loadClass(className, false);
		return null;
	}
	
	boolean isTestClass(Class testClass) {
		if (hasSuiteMethod(testClass))
			return true;
		if (Test.class.isAssignableFrom(testClass) &&
			Modifier.isPublic(testClass.getModifiers()) &&
			hasPublicConstructor(testClass)) 
			return true;
		return false;
	}
	
	boolean hasSuiteMethod(Class testClass) {
		try {
			testClass.getMethod(BaseTestRunner.SUITE_METHODNAME, new Class[0]);
	 	} catch(Exception e) {
	 		return false;
		}
		return true;
	}
	
	boolean hasPublicConstructor(Class testClass) {
		try {
			TestSuite.getTestConstructor(testClass);
		} catch(NoSuchMethodException e) {
			return false;
		}
		return true;
	}
}