1 package org.junit.internal.runners; 2 3 import java.lang.annotation.Annotation ; 4 import java.lang.reflect.Method ; 5 import java.lang.reflect.Modifier ; 6 import java.util.ArrayList ; 7 import java.util.List ; 8 9 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 private final TestIntrospector fIntrospector; 17 18 private final List <Throwable > fErrors= new ArrayList <Throwable >(); 19 20 private final Class <?> fTestClass; 21 22 public MethodValidator(Class <?> testClass) { 23 fTestClass= testClass; 24 fIntrospector= new TestIntrospector(testClass); 25 } 26 27 public void validateInstanceMethods() { 28 validateTestMethods(After.class, false); 29 validateTestMethods(Before.class, false); 30 validateTestMethods(Test.class, false); 31 } 32 33 public void validateStaticMethods() { 34 validateTestMethods(BeforeClass.class, true); 35 validateTestMethods(AfterClass.class, true); 36 } 37 38 public List <Throwable > validateMethodsForDefaultRunner() { 39 validateNoArgConstructor(); 40 validateStaticMethods(); 41 validateInstanceMethods(); 42 return fErrors; 43 } 44 45 public void assertValid() throws InitializationError { 46 if (!fErrors.isEmpty()) 47 throw new InitializationError(fErrors); 48 } 49 50 public void validateNoArgConstructor() { 51 try { 52 fTestClass.getConstructor(); 53 } catch (Exception e) { 54 fErrors.add(new Exception ("Test class should have public zero-argument constructor", e)); 55 } 56 } 57 58 private void validateTestMethods(Class <? extends Annotation > annotation, 59 boolean isStatic) { 60 List <Method > methods= fIntrospector.getTestMethods(annotation); 61 for (Method each : methods) { 62 if (Modifier.isStatic(each.getModifiers()) != isStatic) { 63 String state= isStatic ? "should" : "should not"; 64 fErrors.add(new Exception ("Method " + each.getName() + "() " 65 + state + " be static")); 66 } 67 if (!Modifier.isPublic(each.getDeclaringClass().getModifiers())) 68 fErrors.add(new Exception ("Class " + each.getDeclaringClass().getName() 69 + " should be public")); 70 if (!Modifier.isPublic(each.getModifiers())) 71 fErrors.add(new Exception ("Method " + each.getName() 72 + " should be public")); 73 if (each.getReturnType() != Void.TYPE) 74 fErrors.add(new Exception ("Method " + each.getName() 75 + " should be void")); 76 if (each.getParameterTypes().length != 0) 77 fErrors.add(new Exception ("Method " + each.getName() 78 + " should have no parameters")); 79 } 80 } 81 } 82 | Popular Tags |