01: package org.junit.internal.runners;
02:
03: import java.lang.annotation.Annotation;
04: import java.lang.reflect.Method;
05: import java.lang.reflect.Modifier;
06: import java.util.ArrayList;
07: import java.util.List;
08:
09: import org.junit.After;
10: import org.junit.AfterClass;
11: import org.junit.Before;
12: import org.junit.BeforeClass;
13: import org.junit.Test;
14:
15: public class MethodValidator {
16:
17: private final List<Throwable> fErrors = new ArrayList<Throwable>();
18:
19: private TestClass fTestClass;
20:
21: public MethodValidator(TestClass testClass) {
22: fTestClass = testClass;
23: }
24:
25: public void validateInstanceMethods() {
26: validateTestMethods(After.class, false);
27: validateTestMethods(Before.class, false);
28: validateTestMethods(Test.class, false);
29:
30: List<Method> methods = fTestClass
31: .getAnnotatedMethods(Test.class);
32: if (methods.size() == 0)
33: fErrors.add(new Exception("No runnable methods"));
34: }
35:
36: public void validateStaticMethods() {
37: validateTestMethods(BeforeClass.class, true);
38: validateTestMethods(AfterClass.class, true);
39: }
40:
41: public List<Throwable> validateMethodsForDefaultRunner() {
42: validateNoArgConstructor();
43: validateStaticMethods();
44: validateInstanceMethods();
45: return fErrors;
46: }
47:
48: public void assertValid() throws InitializationError {
49: if (!fErrors.isEmpty())
50: throw new InitializationError(fErrors);
51: }
52:
53: public void validateNoArgConstructor() {
54: try {
55: fTestClass.getConstructor();
56: } catch (Exception e) {
57: fErrors
58: .add(new Exception(
59: "Test class should have public zero-argument constructor",
60: e));
61: }
62: }
63:
64: private void validateTestMethods(
65: Class<? extends Annotation> annotation, boolean isStatic) {
66: List<Method> methods = fTestClass
67: .getAnnotatedMethods(annotation);
68:
69: for (Method each : methods) {
70: if (Modifier.isStatic(each.getModifiers()) != isStatic) {
71: String state = isStatic ? "should" : "should not";
72: fErrors.add(new Exception("Method " + each.getName()
73: + "() " + state + " be static"));
74: }
75: if (!Modifier.isPublic(each.getDeclaringClass()
76: .getModifiers()))
77: fErrors.add(new Exception("Class "
78: + 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: }
|