1package org.junit.internal.runners;
2
3import java.lang.annotation.Annotation;
4import java.lang.reflect.Method;
5import java.lang.reflect.Modifier;
6import java.util.ArrayList;
7import java.util.List;
8
9import org.junit.After;
10import org.junit.AfterClass;
11import org.junit.Before;
12import org.junit.BeforeClass;
13import org.junit.Test;
14import org.junit.runners.BlockJUnit4ClassRunner;
15
16/**
17 * @deprecated Included for backwards compatibility with JUnit 4.4. Will be
18 *             removed in the next release. Please use
19 *             {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}.
20 */
21@Deprecated
22public class MethodValidator {
23
24	private final List<Throwable> fErrors= new ArrayList<Throwable>();
25
26	private TestClass fTestClass;
27
28	public MethodValidator(TestClass testClass) {
29		fTestClass = testClass;
30	}
31
32	public void validateInstanceMethods() {
33		validateTestMethods(After.class, false);
34		validateTestMethods(Before.class, false);
35		validateTestMethods(Test.class, false);
36
37		List<Method> methods= fTestClass.getAnnotatedMethods(Test.class);
38		if (methods.size() == 0)
39			fErrors.add(new Exception("No runnable methods"));
40	}
41
42	public void validateStaticMethods() {
43		validateTestMethods(BeforeClass.class, true);
44		validateTestMethods(AfterClass.class, true);
45	}
46
47	public List<Throwable> validateMethodsForDefaultRunner() {
48		validateNoArgConstructor();
49		validateStaticMethods();
50		validateInstanceMethods();
51		return fErrors;
52	}
53
54	public void assertValid() throws InitializationError {
55		if (!fErrors.isEmpty())
56			throw new InitializationError(fErrors);
57	}
58
59	public void validateNoArgConstructor() {
60		try {
61			fTestClass.getConstructor();
62		} catch (Exception e) {
63			fErrors.add(new Exception("Test class should have public zero-argument constructor", e));
64		}
65	}
66
67	private void validateTestMethods(Class<? extends Annotation> annotation,
68			boolean isStatic) {
69		List<Method> methods= fTestClass.getAnnotatedMethods(annotation);
70
71		for (Method each : methods) {
72			if (Modifier.isStatic(each.getModifiers()) != isStatic) {
73				String state= isStatic ? "should" : "should not";
74				fErrors.add(new Exception("Method " + each.getName() + "() "
75						+ state + " be static"));
76			}
77			if (!Modifier.isPublic(each.getDeclaringClass().getModifiers()))
78				fErrors.add(new Exception("Class " + each.getDeclaringClass().getName()
79						+ " should be public"));
80			if (!Modifier.isPublic(each.getModifiers()))
81				fErrors.add(new Exception("Method " + each.getName()
82						+ " should be public"));
83			if (each.getReturnType() != Void.TYPE)
84				fErrors.add(new Exception("Method " + each.getName()
85						+ " should be void"));
86			if (each.getParameterTypes().length != 0)
87				fErrors.add(new Exception("Method " + each.getName()
88						+ " should have no parameters"));
89		}
90	}
91}
92