001: package org.junit.internal.runners;
002:
003: import java.lang.annotation.Annotation;
004: import java.lang.reflect.Constructor;
005: import java.lang.reflect.Method;
006: import java.util.ArrayList;
007: import java.util.Collections;
008: import java.util.List;
009:
010: import org.junit.AfterClass;
011: import org.junit.Before;
012: import org.junit.BeforeClass;
013: import org.junit.Test;
014:
015: public class TestClass {
016: private final Class<?> fClass;
017:
018: public TestClass(Class<?> klass) {
019: fClass = klass;
020: }
021:
022: List<Method> getTestMethods() {
023: return getAnnotatedMethods(Test.class);
024: }
025:
026: List<Method> getBefores() {
027: return getAnnotatedMethods(BeforeClass.class);
028: }
029:
030: List<Method> getAfters() {
031: return getAnnotatedMethods(AfterClass.class);
032: }
033:
034: public List<Method> getAnnotatedMethods(
035: Class<? extends Annotation> annotationClass) {
036: List<Method> results = new ArrayList<Method>();
037: for (Class<?> eachClass : getSuperClasses(fClass)) {
038: Method[] methods = eachClass.getDeclaredMethods();
039: for (Method eachMethod : methods) {
040: Annotation annotation = eachMethod
041: .getAnnotation(annotationClass);
042: if (annotation != null
043: && !isShadowed(eachMethod, results))
044: results.add(eachMethod);
045: }
046: }
047: if (runsTopToBottom(annotationClass))
048: Collections.reverse(results);
049: return results;
050: }
051:
052: private boolean runsTopToBottom(
053: Class<? extends Annotation> annotation) {
054: return annotation.equals(Before.class)
055: || annotation.equals(BeforeClass.class);
056: }
057:
058: private boolean isShadowed(Method method, List<Method> results) {
059: for (Method each : results) {
060: if (isShadowed(method, each))
061: return true;
062: }
063: return false;
064: }
065:
066: private boolean isShadowed(Method current, Method previous) {
067: if (!previous.getName().equals(current.getName()))
068: return false;
069: if (previous.getParameterTypes().length != current
070: .getParameterTypes().length)
071: return false;
072: for (int i = 0; i < previous.getParameterTypes().length; i++) {
073: if (!previous.getParameterTypes()[i].equals(current
074: .getParameterTypes()[i]))
075: return false;
076: }
077: return true;
078: }
079:
080: private List<Class<?>> getSuperClasses(Class<?> testClass) {
081: ArrayList<Class<?>> results = new ArrayList<Class<?>>();
082: Class<?> current = testClass;
083: while (current != null) {
084: results.add(current);
085: current = current.getSuperclass();
086: }
087: return results;
088: }
089:
090: public Constructor<?> getConstructor() throws SecurityException,
091: NoSuchMethodException {
092: return fClass.getConstructor();
093: }
094:
095: public Class<?> getJavaClass() {
096: return fClass;
097: }
098:
099: public String getName() {
100: return fClass.getName();
101: }
102:
103: }
|